A “defer” statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking. defer语句调用一个函数,这个函数执行会推迟,直到外围的函数返回,或者外围函数运行到最后,或者相应的goroutine panic。
defer 在声明时不会立即执行,而是在函数 return 后,再按照 FILO (先进后出)的原则依次执行每一个 defer,一般用于异常处理、释放资源、清理数据、记录日志等。这有点像面向对象语言的析构函数,优雅又简洁,是 Golang 的亮点之一。
特性1:延迟执行
func readFile(fileName string){
f,err := os.Open(fileName)
if err!=nil {
return
}
defer f.Close()
var content [1024]byte
f.Read(content[:])
fmt.Printf("%s",content)
}
func main() {
readFile("test.data")
}
特性2:先进后出
package main
import "fmt"
func fn(n int) int {
defer func() {
n++
fmt.Println("3st:", n)
}()
defer func() {
n++
fmt.Println("2st:", n)
}()
defer func() {
n++
fmt.Println("1st:", n)
}()
return n //没有做任何事情
}
func main() {
fmt.Println("函数返回值:", fn(0))
}
输出:
1st: 1
2st: 2
3st: 3
函数返回值: 0