package main
import "fmt"
type Student struct {
name string
}
func main() {
var students [2]Student
students[0].name = "fred"
students[1].name = "karen"
var fredPtr *Student
fredPtr = nil
for _, student := range students {
if student.name == "fred" {
fredPtr = &student
}
}
fmt.Println(fredPtr.name)
}
这段代码的输出结果是:
go run for-loop.go
karen
因为 fredPtr 在赋值的时候指向的是student变量,当第一次迭代时,指向fred,但是当第二次迭代时,则会指向karen,这是就会到时结果和预期不一致。
图片表示如下:
正确的写法
package main
import "fmt"
type Student struct {
name string
}
func main() {
var students [2]Student
students[0].name = "fred"
students[1].name = "karen"
var fredPtr *Student
fredPtr = nil
for idx, student := range students {
if student.name == "fred" {
fredPtr = &students[idx]
}
}
fmt.Println(fredPtr.name)
}
参考原文:Go is Not Python