基本用法
- 参数会在 defer 方法执行时,固化
func a() {
i := 0
defer fmt.Println(i) // 0
i++
return
}
- 执行顺序后进先出
func b() {
for i := 0; i < 4; i++ {
defer fmt.Print(i)
}
}
// 3210
- 操作返回值变量
func c() (i int) {
defer func() { i++ }()
return 1
}
调整错误返回值
func Create() (err error) {
defer func() {
if err != nil {
db.Rollback()
} else {
err = db.Commit()
}
}()
}
示例:
func CopyFile(dstName, srcName string) (written int64, err error) {
src, err := os.Open(srcName)
if err != nil {
return
}
defer src.Close()
dst, err := os.Create(dstName)
if err != nil {
return
}
defer dst.Close()
return io.Copy(dst, src)
}
defer 可嵌套使用
package main
import (
"fmt"
)
func main() {
defer func() {
defer func() {
fmt.Println("Inner defer")
}()
fmt.Println("Outer defer")
}()
fmt.Println("Execution finished")
}
// Execution finished
// Outer defer
// Inner defer
配合 panic
package main
import "fmt"
func main() {
f()
fmt.Println("Returned normally from f.")
}
func f() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
}
}()
fmt.Println("Calling g.")
g(0)
fmt.Println("Returned normally from g.")
}
func g(i int) {
if i > 3 {
fmt.Println("Panicking!")
panic(fmt.Sprintf("%v", i))
}
defer fmt.Println("Defer in g", i)
fmt.Println("Printing in g", i)
g(i + 1)
}
// Calling g.
// Printing in g 0
// Printing in g 1
// Printing in g 2
// Printing in g 3
// Panicking!
// Defer in g 3
// Defer in g 2
// Defer in g 1
// Defer in g 0
// Recovered in f 4
// Returned normally from f.