i have instance of struct has array field. when goroutine replaces array on instance, other handles instance still have original array. why this? should change instance of container
below reflect change made on goroutine?
a simple example reflected here: https://play.golang.org/p/dxvkn6o8ap
func create() container { instance := *&container{ values: []string{"initial value"}, } go func() { instance.values = []string{"modified value"} fmt.print("values updated") }() return instance } func main() { instance := create() time.sleep(100 * time.millisecond) fmt.printf("%[1]v", instance.values) //prints "initial value", expected "modified value" }
it because using slice's value. return value of slice returned main
copy. goroutine executes , updates original value. make following changes:
func create() *container { // return pointer container // instance initialized , points container value // (i.e. instance of type *container) instance := &container{ values: []string{"initial value"}, } go func() { instance.values = []string{"modified value"} fmt.print("values updated") }() return instance }
now main has pointer above instance
, modifications done goroutine visible.
example: https://play.golang.org/p/akwuzftu0s
also, create new value, can directly use type's name:
instance := container{ // instance of type container // ... }
and create , initialize pointer of type, use:
instance := &container{ // instance of type *container // ... }
doing below redundant:
instance := *&container{ // instance of type container. same first declaration // ... }
Comments
Post a Comment