[cpp]
// xxxxxxxxxxxxxxxxxxxxxx project main.go
package main
import (
"fmt"
)
func test() (int, int) {
return 1, 2
}
func main() {
i, j := test()
i, j := test()
fmt.Println("%d %d", i, j)
}
[/cpp]
报错 :15: no new variables on left side of :=
[cpp]
package main
import (
"fmt"
)
func test() (int, int) {
return 1, 2
}
func main() {
i, j := test()
k, j := test()
fmt.Println("%d %d %d", i, j, k)
}
[/cpp]
不报错
貌似说明用了:=后 至少得有一个变量是未知类型的,否则提示没有新的变量在:=的左侧。
//////////////////////////////////////////////////////////////////////////////////////////////////////////
[cpp]
// xxxxxxxxxxxxxxxxxxxxxx project main.go
package main
import (
"fmt"
)
type st struct {
d int
}
func test() (int, int) {
return 1, 2
}
func main() {
var x st
i, j := test()
x.d, j := test()
fmt.Println("%d %d %d", i, j, x.d)
}
[/cpp]
报错 :20: non-name x.d on left side of :=
[cpp]
// xxxxxxxxxxxxxxxxxxxxxx project main.go
package main
import (
"fmt"
)
type st struct {
d int
}
func test() (int, int) {
return 1, 2
}
func main() {
var x st
i, j := test()
x.d, k := test()
fmt.Println("%d %d %d %d", i, j, x.d, k)
}
[/cpp]
报错 :20: non-name x.d on left side of :=
这说明 := 不能给结构体成员赋值?
[cpp]
package main
import (
"fmt"
)
type st struct {
d int
}
func test() (int, int) {
return 1, 2
}
func main() {
var x st
i, j := test()
x.d, j = test()
fmt.Println("%d %d %d", i, j, x.d)
}
[/cpp]
不报错
官方解释 http://golang.org/ref/spec#Short_variable_declarations
Short variable declarations
A short variable declaration uses the syntax:
ShortVarDecl = IdentifierList ":=" ExpressionList .
It is a shorthand for a regular variable declaration with initializer expressions but no types:
"var" IdentifierList = ExpressionList .
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 coordinate
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block 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.
第三四个例子网上也有人讨论 https://groups.google.com/forum/#!msg/golang-nuts/ItYSNKqt_kA/OLGaOoDtCHgJ
感谢 http://v2ex.com/t/87324 里的 wwwjfy