I'm a little bit confused with result from below code:
func change(v *int) bool {
*v = 3
return true
}
func value(v int) int {
return v
}
func main() {
b := 1
fmt.Println(b + 1, value(b + 1), change(&b))
}
Output:
4 2 true
I expected 2 2 true. Then I checked spec
<https://golang.org/ref/spec#Order_of_evaluation>, it said:
"all function calls, method calls, and communication operations are
evaluated in lexical left-to-right order."
and:
"However, the order of those events compared to the evaluation and
indexing of x and the evaluation of y is not specified."
So from that we can say both 4 2 and 2 2 are correct based on spec,
although the implementation choose putting expression evaluated after all
the function calls.
I think it's better written into spec rather than say not specified. Why?
because I already see some production code with below pattern:
.....
return b, change(&b)
}
(the real production code use a function closure which directly modify b
without pointer, but I think the order issue is same)
I don't know if this pattern is used a lot in other place since I'm still
new to golang, but people writing go style probably like this way. Since it
depends on a not specified behavior which has risk to change in future and
very hard to debug, I think it's better written into spec which make sure
it won't change in future.
Any thoughts?
Thanks.
--
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 [email protected].
For more options, visit https://groups.google.com/d/optout.