结构变量未更新 [英] Struct variable not being updated

查看:68
本文介绍了结构变量未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array in test code

arr := []Server{}

要求arr [0] .GetId()

which asks for arr[0].GetId()

服务器是接口。
ServerInstance是实现接口方法的结构,即

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

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

我有一个类似

func (serv *ServerInstance) someFunc

正在更新结构的变量 Id。我确定值会更新为-

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

serv.Id=23445

但这并不反映在第3行的通话中

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)
}

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

推荐答案

在添加结构时,您正在复制它们,而不是在示例中放置指向结构本身的指针。 http://play.golang.org/p/rQz9RLTzMU -可以正常工作吗?
进一步的信息:Golang是一种按值传递的语言,因此,如果您使用goroutines并希望保持数据的安全性,最好使用指针。

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.

这篇关于结构变量未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆