dsfsda121545 2018-03-23 19:17 采纳率: 0%
浏览 10
已采纳

为什么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.

  • 写回答

2条回答 默认 最新

  • dongra1984 2018-03-23 19:24
    关注
    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?