Consider the following Go function (playground), which was evaluated with Go 1.8:
func f() (int, bool) {
i := 0
c := make(chan bool)
go func() {
time.Sleep(1 * time.Second)
i = 1
c <- true
}()
// In practice, `i` will always be 0 here.
return i, <-c // returns 1, true
}
As stated in the comments, the function seem to always copy i
after c
has yielded a value. As this happens ~1s after encountering the return statement, this is not what I expected.
The behavior is the same if the value order is reversed in the return and also if the return is replaced by assignment.
Note that I'm not claiming this behavior to be wrong - just unexpected. In fact, this will almost always be what you want to happen.
The question therefore is if this intended/specified behavior that can be relied on?
The spec section on the receive operator doesn't state exactly when it blocks the thread in cases like this.