#what is the difference between passing some value to go routine and using the value from outside

7 messages · Page 1 of 1 (latest)

spare python
#

// type A
func Query(conns []Conn, query string) Result {
ch := make(chan Result, len(conns))
for _,chan := range conns {
go func(c conn) {
ch <- c.DoQuery(query)
}(conn)
}
Result <- ch
}

// type B
func Query(conns []Conn, query string) Result {
ch := make(chan Result, len(conns))
for _,chan := range conns {
go func() {
ch <- c.DoQuery(query)
}()
}
Result <- ch
}

What is the difference btw type A and B ?

stable compass
#

A is correct, B is subtly incorrect.

In B every goroutine is sharing the same c variable, which means that the value they read depends on when they read it.
https://go.dev/doc/faq#closures_and_goroutines covers this in more detail, but if you have any followup questions feel free to ask!

spare python
#

the link helped. so if we give like v := v, which is basically creating a new memory address variable, and that solves a problem?

stable compass
#

that's one way to do it yeah, it's more common to do that when there are no goroutines involved, otherwise I think the consensus is to just pass parameters as it's much clearer

spare python
#

makes sense.
So this paradigm is good if there is a loop involved and inside the goroutines we are using the loop value

#

is there some other instance that you can give an example to ?

stable compass
#

well there's tons of ways to write incorrect code so not really.
this is the most common instance where it's more of a "gotcha" than programmer error as it goes against what an unknowing programmer would expect