Golang: Variables
var name type
- Declare a variable.
var name2, name2, name3 … type
- Delare variables name1 etc, all of type type.
package main import "fmt" var x int var y float32 var z string var a, b, c int func main() { fmt.Printf("%#v %#v %#v\n", x, y, z) // 0 0 "" // the %#v means show in golang syntax. else, empty string won't be displayed fmt.Printf("%#v %#v %#v\n", a, b, c) // 0 0 0 }
Default Value (Zero Value)
When variable is declared but not assigned a value yet, it gets its default value. Different type of value has different default values. The default values are called zero value [see Golang: Zero Value]
For int type, default is 0.
Variable with Value
A var declaration can also have value. (golang calls this Initialization.)
var x = 3
If given a value, then its “type” can be omitted in the declaration. Golang will infer the type.
package main import "fmt" func main() { // var declaration, with assignment var x = 3 // no type. golang can infer the type fmt.Println(x) // 3 // print its type fmt.Printf("%T\n", x) // int }
Parallel Assignment
var x, y, z = 3, 4, 1
- Declare and assign multiple variables.
package main import "fmt" func main() { var x, y = 3, 4 fmt.Println(x, y) // 3 4 }
Note: it's common to see the following, when a function return multiple values.
var x, y = f(3)
[see Golang: Function]
Variable Scope
- Variables in a package are local to the package.
- Variables inside function are local to the function.
package main import "fmt" // package level variable var x = 3 func main() { // function level variable var y = 4 fmt.Println(x, y) // 3 4 }
Variable Syntax Shortcut Inside Function
Inside a function, the syntax
name := val
is the same as
var name = val
[see Golang: Function]
package main import "fmt" func main() { k := 3 fmt.Println(k) } // 3
Grouping Variable Declaration
Alternative syntax for variable is to have var
only appear once, like this:
var (name1 type1; name1 type2 …)
or
var (name1 = val1; name2 = val2 …)
package main import "fmt" var ( a int b = 2 c = "some" d int ) func main() { fmt.Println(a, b, c, d) // 0 2 some 0 }
Note: Semicolon ; is optional when it is at end of line.