go 语言 for循环的一个坑
1、案例1
package main import "fmt" type Card struct { id int } func main() { list := make([]*Card, 0) card := &Card{} for index := 1; index < 10; index++ { card.id = index list = append(list, card) } //fmt.Println(list) for _, c := range list { fmt.Println(*c) } }
输出结果:
2、案例2
package main import "fmt" type Card struct { id int } func main() { list := make([]*Card, 0) card := &Card{} for index := 1; index < 10; index++ { card = &Card{ id: index, } list = append(list, card) } for _, c := range list { fmt.Println("Card", c) } }
输出结果:
3、案例3
package main import "fmt" type Card struct { id int } func main() { list := make([]*Card, 0) for index := 1; index < 10; index++ { card := &Card{} card.id = index list = append(list, card) } for _, c := range list { fmt.Println("Card", c) } }
输出结果:
4、闭包和协程
package main import ( "fmt" "time" ) func main() { for i := 0; i < 10; i++ { go func() { fmt.Println(i) }() // 输出全部为10 } time.Sleep(time.Second) }
在每个协程中,从进入匿名函数到调用Println将i
的值复制入栈之间仍需要一小段时间运行,而这段时间内足以主线程完成全部10次循环。所以终于到将i
的值复制入栈调用Println时,i
已经成为10且不再变化了