Go - defer

2024-12-21  本文已影响0人  隐号骑士

Go's defer statement schedules a function call (the deferred function) to be run immediately before the function executing the defer returns. It's an unusual but effective way to deal with situations such as resources that must be released regardless of which path a function takes to return. The canonical examples are unlocking a mutex or closing a file.

package main

import "fmt"

func main() {
    defer fmt.Println("This is the last statement in main.") 

    fmt.Println("Starting main...")

    defer fmt.Println("This is the second deferred statement.") 

    fmt.Println("End of main.")
}

output:

// LIFO
Starting main...
End of main.
This is the second deferred statement.
This is the last statement in main.

The arguments to the deferred function (which include the receiver if the function is a method) are evaluated when the defer executes, not when the call executes.

package main

import "fmt"

func main() {
    i := 0
    defer fmt.Println(i)
    i++
}

output:

0
上一篇 下一篇

猜你喜欢

热点阅读