Variables in Go Programming Language
Variable declaration using var keyword
we can declare variables in Golang using var keyword like below
var name string
var address string
var age int
we can also declare multiple variables with single keyword like below
var(
name string
address string
age int
)
var(
name, address string
age int
)
Example program
package main
import "fmt"
func main() {
var(
name string
age int
address string
weight float64
height float32
isHeayWeight bool
)
fmt.Printf("name:%s,age:%d,address:%s,weight:%f,height:%f,isHeayWeight:%t \n",
name,age,address,weight,height,isHeayWeight)
}
You can run this program live here https://onecompiler.com/go/3usz2cqnz
Output
name:,age:0,address:,weight:0.000000,height:0.000000,isHeayWeight:false
Type Interface
In Golang we do not mention the type of the variable explicitly, based on value it infers the type of the variable
var name = "onecompiler"
basing on above declaration it infers the type of name variable to String.
If we changes the value from string to number it will throw compilation error.
var name ="onecompiler" //infers string type
name = 1234 //throws compilation error
Type inference allows us to declare and initialise multiple variables of different data types in a single line.
Example
package main
import "fmt"
func main() {
// Multiple variable declarations with inferred types
var name, address, age, salary = "OneCompiler", "Hyderabad", 28, 50000.0
fmt.Printf("name: %T, address: %T, age: %T, salary: %T\n",
name, address, age, salary)
fmt.Printf("name: %s, address: %s, age: %d, salary: %f\n",
name, address, age, salary)
}
You can run this program live here https://onecompiler.com/go/3usz35ua4
Output
name: string, address: string, age: int, salary: float64
name: OneCompiler, address: Hyderabad, age: 28, salary: 50000.000000
Short Declaration
we can declare variables shortly in Golang using := operator
Example
package main
import "fmt"
func main() {
// Short variable declaration syntax
name := "OneCompiler"
age, salary, isExcellentSite := 35, 50000.0, true
fmt.Println(name, age, salary, isExcellentSite)
}
Output
OneCompiler 35 50000 true