3 ms·
I think you posted this comment on the wrong post, but anyway: In this case, no, and it's actually slightly inefficient to pass those variables as arguments, b
by jamespwilliams 6y ago
I think you posted this comment on the wrong post, but anyway:
In this case, no, and it's actually slightly inefficient to pass those variables as arguments, because a copy of the argument has to be made. This copying matters more if the argument is a big struct or another large value.
However often it is useful to use arguments, for example when calling a goroutine in a loop. For example:
for i := 0; i < 10; i++ {
go func() {
fmt.Println(i)
}()
}
vs
for i := 0; i < 10; i++ {
go func(i int) {
fmt.Println(i)
}(i)
}
have different behaviours, because the first receives the (changing) `i` variable itself, whereas the second receives a copy of `i` at each iteration. The second behaviour is often the behaviour we actually want.
Something like
for i := 0; i < 10; i++ {
i := i
go func() {
fmt.Println(i)
}()
}
also works as expected.
- DelightOne 6y agoAh I didnt realize I had the wrong post open, it was supposed to be on the Go Generics examples post. Thank you that makes sense!