defer
下面举例说明了defer语句的作用:
package main
import "fmt"
func main() {
i := 10
defer incr(i)
defer incr2(i)
defer incr3(i)
}
func incr(i int){
j := i -1
fmt.Println(j)
}
func incr2(i int){
j := i -2
fmt.Println(j)
}
func incr3(i int){
j := i -3
fmt.Println(j)
}
输出结果:
GOROOT=C:\Go #gosetup
GOPATH=C:\Users\DELL\go #gosetup
C:\Go\bin\go.exe build -o C:\Users\DELL\AppData\Local\Temp\___go_build_cmpl_go.exe C:/Users/DELL/ActiveGo/src/spider/main/cmpl.go #gosetup
"C:\Program Files\JetBrains\GoLand 2018.3.2\bin\runnerw64.exe" C:\Users\DELL\AppData\Local\Temp\___go_build_cmpl_go.exe #gosetup
7
8
9
Process finished with exit code 0
很明显 defer语句的执行顺序是反的。这种语法给我们的资源关闭提供了很好的帮助。
比如流的关闭啊,文件的关闭啊等等。
有疑问加站长微信联系(非本文作者)