cxfans
11/27/2019 - 4:56 AM

range复用临时变量

range复用临时变量

package main

import "sync"

func range1() {
	wg := sync.WaitGroup{}
	s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	for _, i := range s {
		wg.Add(1)
		go func() {
			println(i)
			wg.Done()
		}()
	}
	wg.Wait()
}

func range2() {
	wg := sync.WaitGroup{}
	s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	for _, i := range s {
		wg.Add(1)
		go func(i int) {
			println(i)
			wg.Done()
		}(i)
	}
	wg.Wait()
}

func main() {
	range1()
	range2()
}