Struct variable not being updated

点点圈 提交于 2019-12-20 06:34:40

问题


I have an array in test code

arr := []Server{}

which asks for arr[0].GetId()

Server is an interface. ServerInstance is a struct implementing a method of interface, i.e

func (serv ServerInstance) GetId() int {
    return serv.Id
}

I have a goroutine like

func (serv *ServerInstance) someFunc

which is updating a variable 'Id' of struct. I am sure of value being updated as -

serv.Id=23445

But this is not being reflected in call at line 3

*Update***

for somecondition {
     arr=append(arr,FuncReturningServerIntercae() // calling this invokes goroutine which keeps updating `Id` very frequently
}


for {
   for _,s := range arr {
        print s.GetId()   // ** No Update **
     }
    sleep(some duration)
}

** Example ** http://play.golang.org/p/zUqJ0hEjxv


回答1:


You're copying the structs when appending them, rather than placing pointers to the structs themselves in the example. http://play.golang.org/p/rQz9RLTzMU -- works as intended yes? Further info: Golang is a pass-by-value language, so if you're using goroutines and you want to keep the sanctity of your data, you'd be better off using pointers.



来源:https://stackoverflow.com/questions/21786624/struct-variable-not-being-updated

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!