package main
import(
"fmt"
"time"
)
func main(){
fmt.Println("1")
defer fmt.Println("-1")
go func() {
fmt.Println("2")
defer fmt.Println("-2")
time.Sleep(9 * time.Second)
}()
time.Sleep(1 * time.Second)
fmt.Println("3")
}
Produces the output: 1 2 3 -1 But I would've thought the goroutine's defer would have been called to produce: 1 2 3 -2 -1
In my actual code my goroutine is blocked on a websocket... I suppose I could send a shutdown signal but I haven't yet figured out how to do a wait-on-multiple-objects kind of thing (if it can actually be done in go). I'm currently solving my problem by hoisting the deferred -2 into the main scope.
Is there some trick to defer placement I'm not doing right?