Hello awesome community!

I am so honored to be a part of the great community of gophers around the 
world. Thank you to everyone who makes it so inviting to everyone who wants 
to participate. 

I am writing today to ask about some puzzling behavior with respect to 
dereferencing pointers, function evaluation and tuple assignment. I have 
the following code snippet:

type T struct {
i int
}

func (t *T) sideEffectPtr() *int {
t.i += 4
return &t.i
}

func derefIntPtr(i *int) int {
return *i
}

func main() {
var d = T{i: 200}
var e = T{i: 200}
a, b := derefIntPtr(d.sideEffectPtr()), derefIntPtr(d.sideEffectPtr())
aa, bb := *e.sideEffectPtr(), *e.sideEffectPtr()
fmt.Println(a, b)
fmt.Println(aa, bb)
}

You can see the code in action on the playground here: 
https://play.golang.org/p/wGsvYWXEqf

The output is surprising, to say the least:
204 208 
208 208


>From what I understand, the right hand side of a tuple assignment is 
completely evaluated before the assignment happens. I also think that I 
understand that for evaluations not covered specifically by the language 
specification, the particular order of the evaluation is not defined. In 
other words, in

aa, bb := *e.sideEffectPtr(), *e.sideEffectPtr()

the calls to sideEffectPtr() may happen in any order. 

However, I would imagine that, no matter what the order, the dereference 
operation would happen immediately after the first function call and before 
the second. That would lead me to believe that one output would be 204 and 
the other would be 208. 

Indeed that is what happens when you perform the dereference operation via 
a function:

a, b := derefIntPtr(d.sideEffectPtr()), derefIntPtr(d.sideEffectPtr())

but that is NOT what happens when you use the * operator directly. 

I have spent a significant amount of time thinking about this and 
consulting (what I think) is the relevant part of the spec: 
https://golang.org/ref/spec#Order_of_evaluation. I've tried to write a 
relatively succinct test case and provide this brief description.

If anyone can shed light on what I am missing, I would really appreciate 
it. 

Again, thank you so much for creating such a great community and for any 
time that you can spare to help me through this issue.

Will

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to