# 循环

Last Updated: 2023-02-23

## 入门。

``````for k, v := range []int{1, 3, 5, 7} {
fmt.Printf("key = %v, value = %v\n", k, v)
}
``````
``````key = 0, value = 1
key = 1, value = 3
key = 2, value = 5
key = 3, value = 7
``````

## 放弃？

``````// 创建一个WaitGroup来跑多个goroutines
var wg sync.WaitGroup
for k, v := range []int{1, 3, 5, 7} {
// 增加WaitGroup的计数
go func() {
// 结束的时候别忘了通知WaitGroup
defer wg.Done()
// 假装很忙
time.Sleep(time.Second)
fmt.Printf("key = %v, value = %v\n", k, v)
}()
}
wg.Wait()
``````

``````key = 3, value = 7
key = 3, value = 7
key = 3, value = 7
key = 3, value = 7
``````

``````done := make(chan bool)
values := []int{1, 3, 5, 7}
for k, v := range values {
go func() {
time.Sleep(time.Second)
fmt.Printf("key = %v, value = %v\n", k, v)
done <- true
}()
}
for range values{
<-done
}
``````

``````key = 3, value = 7
key = 3, value = 7
key = 3, value = 7
key = 3, value = 7
``````

## 进阶！

``````for k, v := range []int{1, 3, 5, 7} {
go func(k, v int) {
defer wg.Done()
time.Sleep(time.Second)
fmt.Printf("key = %v, value = %v\n", k, v)
}(k, v)
}
``````

``````for k, v := range []int{1, 3, 5, 7} {
k := k
v := v