结构变量未被更新

huangapple go评论86阅读模式
英文:

Struct variable not being updated

问题

我在测试代码中有一个数组:

arr := []Server{}

它要求获取 arr[0].GetId()

Server 是一个接口。

ServerInstance 是一个实现接口方法的结构体,例如:

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

我有一个类似的 goroutine:

func (serv *ServerInstance) someFunc

它正在更新结构体的变量 Id。我确定值已经更新了,比如:

serv.Id = 23445

但是在第 3 行的调用中没有反映出来。

更新

for somecondition {
    arr = append(arr, FuncReturningServerInterface()) // 调用此函数会调用一个频繁更新 `Id` 的 goroutine
}

for {
    for _, s := range arr {
        print s.GetId() // ** 没有更新 **
    }
    sleep(some duration)
}

示例
http://play.golang.org/p/zUqJ0hEjxv

英文:

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

得分: 3

你在添加结构体时是复制结构体,而不是在示例中放置结构体本身的指针。http://play.golang.org/p/rQz9RLTzMU -- 这样做是有意义的,对吗?
更多信息:Golang 是一种按值传递的语言,所以如果你在使用 goroutine 并且想要保持数据的完整性,最好使用指针。

英文:

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.

huangapple
  • 本文由 发表于 2014年2月15日 02:14:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/21786624.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定