Golang: Variables
Declare Variable Without Value
var name type
-
Declare a variable.
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 }
var name2, name2, name3, etc type
- Delare variables name1 etc, all of type type.
Default Value (Zero Value)
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)
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; etc)
or
var (name1 = val1; name2 = val2; etc)
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.