Last active
June 27, 2020 11:07
-
-
Save ezaurum/4f23c90f322ef403af4372c74d1b2346 to your computer and use it in GitHub Desktop.
range 로 만든 변수를 사용시 고려할 점
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
var ( | |
test = []string{ | |
"11B804806F367001", | |
"11B804806F367002", | |
"11B804806F767051", | |
} | |
) | |
func main() { | |
wg := sync.WaitGroup{} | |
wg.Add(len(test) * 2) | |
for i, s := range test { | |
// 결과가 생각한 대로 나오나요? | |
go func() { | |
fmt.Printf("start %d - %s\n", i, s) | |
wg.Done() | |
}() | |
// 이 라인은 어째서 쓸까요? :D | |
idx, str := i, s | |
go func() { | |
fmt.Printf("start2 %d - %s\n", idx, str) | |
wg.Done() | |
}() | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
고루틴은 for가 다 돌고 나서 실행될 수도 있고, 중간에 실행될 수도 있습니다. 하지만 for문이 도는 속도가 더 빠를 것이므로 보통의 경우는 다 돌고 내부로직이 돌겠죠.
마지막 값을 가지고 있는 것도 맞습니다.
그 원인은 for 내부에서 i, s를 재사용하기 때문입니다.
맞습니다.
그래서 for 내부에서는 값 사용에 주의해야 합니다.
맞습니다. 고루틴은 실행 순서를 보장하지 않습니다.