为什么golang“推迟”的范围是功能,而不是词汇框[关闭]

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:

  1. is my understanding correct?
  2. 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.

  1. Is my understanding correct?

Yes.

  1. Is there a way to scope it to the block [...]?

There is no way to change how defer works. Depending on the problem you are trying to solve, perhaps splitting your function (example) or defining anonymous functions (example) would help. The latter just for reference and probably best avoided because of how it makes the code less readable.

More info on defer at Go Spec.

Correct?

Yes.

Why?

If you can only have one behavior, function vs. block, which one is easier to define the other?

  • Suppose defer works on block. If you want to defer to a wider scope, you can't. Sometimes, Go requires you to enter a new block, like in if statements, which makes it hard to control easily when defer is applied.

  • Now, if defer is scoped by functions, then you can easily add a new function to shrink the scope. You can even have an anonymous function that you call directly.

    func() {
        defer ...
    }()