Carefully with go keyword in GOLANG
when you are using go keyword in Golang, it means that you are programming concurrency.
So whatever you passed your variable to the concurrent function, the variable should be considered as a local variable of the function
The below example is so popular and it can cause an unexpected error in your code
the variable v is a local variable in for loop, but it is a concurrent variable in process func
When you passed v to the process(v) func, then it might cause issue because two process(v) are able to read the same value of v
So the best way to implement is as below
So whatever you passed your variable to the concurrent function, the variable should be considered as a local variable of the function
The below example is so popular and it can cause an unexpected error in your code
func main() { slice := []Model{ { x: sql.NullString{ String: "1", Valid: true, }, y: 1, z: "1", }, { x: sql.NullString{ String: "2", Valid: true, }, y: 2, z: "2", }, { x: sql.NullString{ String: "3", Valid: true, }, y: 3, z: "3", }, } c := make(chan int, 3) for i, v := range slice { log.Println(i, v) log.Printf("1---> %v \n",&v.y) go func() { process(v, c) }() } for range slice { select { case <-c: } } } func process(model Model, c chan int) { log.Println(model.x, model.y, model.z) c <- model.y} type Model struct { x sql.NullString y int z string
}
the variable v is a local variable in for loop, but it is a concurrent variable in process func
When you passed v to the process(v) func, then it might cause issue because two process(v) are able to read the same value of v
So the best way to implement is as below
go func(model Model) { process(model, c) }(v)
Comments
Post a Comment