Variable Declarations
Syntax
VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
Example
var i int
var U, V, W float64
var k = 0
var x, y float32 = -1, -2
var (
i int
u, v, s = 2.0, 3.0, "bar"
)
var re, im = complexSqrt(-1)
var _, found = entries[name] // map lookup; only interested in "found"
- If no type is specified in the declaration, the default type of the literal or the type of the right hand side is used as the type of the variable.
- If no value is provided, it will use the zero value of the corresponding type to initalize.
Short Variable Declarations
Syntax
ShortVarDecl = IdentifierList ":=" ExpressionList .
Example
- It can be used for multiple declaration at the same time:
i, j := 0, 10
- Declare a function:
f := func() int { return 7 }
- Declare a potiner:
ch := make(chan int)
- Omit some values:
r, w, _ := os.Pipe() // os.Pipe() returns a connected pair of Files and an error, if any
Attention
- Short variable declaration can't be used for global variable declaration, since it can only appears within
blocks
.
- It can be used as long as one variable on the left hand side is not initialized, the already declared vairables will be downgraded to assignments.
field1, offset := nextField(str, 0)
field2, offset := nextField(str, offset) // still OK, redeclares offset
- We can't do double declaration like:
a, a := 1, 2
Reference
- The Go Programming Language Specification