0

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

6
  • 1
    well you are sure, but you wiill have to show some code for somone to help Commented Feb 14, 2014 at 18:16
  • Which part do you doubt? Commented Feb 14, 2014 at 18:19
  • If the call at line 3 is in a separate goroutine, it's possible that your id hasn't been updated yet? Commented Feb 14, 2014 at 18:24
  • just after the assignmet serv.Id=23445 , I printf to verify Commented Feb 14, 2014 at 18:27
  • 1
    There are a lot of things that could go wrong... It's hard to say without seeing a small, simple example. Can you boil it down to the relevant snippet and post the code or a link to play.golang.org or some such? Commented Feb 14, 2014 at 18:29

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I get "Snippet not found" from that link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.