On Thu, Mar 14, 2019 at 2:49 PM zshi via golang-nuts <golang-nuts@googlegroups.com> wrote: > > 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, 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?
This kind of discussion has been had several times, e.g., https://golang.org/issue/23735. In general I don't think there has been a strong sentiment for precisely specifying evaluation order down to the level of exactly when the value of a variable is evaluated. The advantage of doing so is that code such as you describe becomes precisely specified. The disadvantage is that the compiler has much less scope for optimization. In general, code such as you describe is confusing and hard to read. It's impossible to recommend that people write code that way. And if we make that unclear code precisely specified, then the compiler will be forced to generate slower code even for clear code. So well there is an argument for fully specifying the code as you suggest, there is also an argument for leaving it unspecified. Ian -- 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.