Let's say I have a struct with state, and a few member functions on that struct. Let's say that the struct member returns an instance of its own type, and I call additional functions on that instance, and pass the result of calling some other member on the initial instance as an argument. Is the order of invocation between the first invocation, and the argument invocation, guaranteed?
(This pattern comes up a lot when trying to build "builder" type objects that have some internal state, like an expression stack.)
package main
import (
"fmt"
)
type q struct {
val int
}
func (s *q) getVal() int {
return s.val
}
func (s *q) a() *q {
s.val += 1
return s
}
func (s *q) b(i int) int {
return i + s.val
}
func main() {
s := &q{}
// this currently prints 2
// but is that guaranteed?
fmt.Println(s.a().b(s.getVal()))
}
Specifically, is the relative invocation order of s.a()
versus s.getVal()
guaranteed?
Golang defines the "lexical left-to-right order," but only for an individual expression, and s.a().b()
seems like it's technically a different expression than s.getVal()
.
The behavior it currently has is the behavior I'd want and expect, but I can't tell whether it's also a behavior I can rely on "forever."