douzi5214 2014-02-14 18:14
浏览 8
已采纳

结构变量未更新

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条回答 默认 最新

  • dongshetao1814 2014-02-14 19:07
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?