A short variable declaration uses the syntax:
IdentifierList := ExpressionList
It is shorthand for a regular variable declaration with initializer expressions but no types:
var IdentifierList = ExpressionList
example:
i, j := 0, 10
f := func() int { return 7 }
ch := make(chan int)
r, w := os.Pipe(fd) // os.Pipe() returns two values
_, y, _ := coord(p) // coord() returns three values; only interested in y
概括:短变量声明只需要指定变量标识符以及对应的值列表,编译器会根据值的类型自动推导出变量的类型。
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
不同于常规变量声明,在相同块中且至少有一个新的非空白变量的短变量声明中,可对原先声明的变量以相同的类型重声明。因此,重声明只能出现在多变量的短声明中。 重声明没有生成新的变量;它仅仅赋予新的值给原来的变量。
field1, offset := nextField(str, 0)
field2, offset := nextField(str, offset) // redeclares offset
a, a := 1, 2 // illegal: double declaration of a or no new variable if a was declared elsewhere
Short variable declarations may appear only inside functions.
In some contexts such as the initializers for "if", "for", or "switch" statements, they can be used to declare local temporary variables