Use of defer in Go

前端 未结 6 1593
谎友^
谎友^ 2020-12-13 12:45

What is the use of defer in Go? The language documentation says it is executed when the surrounding function returns. Why not just put the code at end of given

6条回答
  •  难免孤独
    2020-12-13 13:11

    A defer statement defers the execution of a function until the surrounding function returns.

    This example demonstrates defer functionality:

    func elapsed(what string) func() {
        start := time.Now()
        fmt.Println("start")
        return func() {
            fmt.Printf("%s took %v\n", what, time.Since(start))
        }
    }
    
    func main() {
        defer elapsed("page")()
        time.Sleep(time.Second * 3)
    }
    

    Out:

    start
    page took 3s
    

提交回复
热议问题