I was surprised to find that these two programs produce the same output:
Program A
package main
import "fmt"
func main() {
defer fmt.Println(1)
defer fmt.Println(2)
}
Program B
package main
import "fmt"
func main() {
{
defer fmt.Println(1)
}
defer fmt.Println(2)
}
In other words, the "defer" statement appears to disregard lexical closures [edit: Thanks to @twotwotwo for correcting my terminology, I meant to say "block" not "lexical closure"] and is strictly scoped to the function. I wondered:
- is my understanding correct?
- is there a way to scope it to the block so that it triggers upon exiting the closure, not the function?
I can imagine doing several units of work in sequence, each requiring its own resource to be closed before proceeding... would be nice not to have to break them into separate functions solely for that purpose.