(no title)
jdreaver | 4 years ago
package main
import "fmt"
func main() {
closure := make_closure()
fmt.Println("closure():", closure())
}
func make_closure() func() int {
x := 1
return func() int { return x }
}
This prints: $ go run main.go
closure(): 1
If x were allocated on the stack, it would get nuked after we returned from make_closure(). In Rust you could move x to the closure, but I think in this Go example x would be heap allocated, assuming the Go compiler doesn't notice it can inline all of this and avoid allocating. Maybe assume a more complex example with a struct that had to be computed via a function argument or something :)
kgeist|4 years ago