go语言常见陷阱
(英文原文)[https://deadbeef.me/2018/01/go-gotchas]
Range
在golang中我们经常用range来遍历slice或chan,如果要更改slice中的成员应该怎么做?下面代码要把动物园中所有动物的腿变为999
type Animal struct {
name string
legs int
}
func main() {
zoo := []Animal{ Animal{ "Dog", 4 },
Animal{ "Chicken", 2 },
Animal{ "Snail", 0 },
}
fmt.Printf("-> Before update %v\n", zoo)
for _, animal := range zoo {
// Oppps! `animal` is a copy of an element
animal.legs = 999
}
fmt.Printf("\n-> After update %v\n"