1.defer 延迟函数
Go的defer语句将函数调用( 延迟函数)计划为在执行defer返回的函数之前立即运行。这是处理异常情况的一种不寻常但有效的方法,例如无论函数返回哪个路径都必须释放资源。典型的例子是解锁互斥锁或关闭文件。
package main
//this function is main run.
import (
"fmt"
"awesomeProject1/morestrings"
)
func trace(s string) { fmt.Println("entering:", s) }
func untrace(s string) { fmt.Println("leaving111:", s) }
func untrace1(s string) { fmt.Println("leaving222:", s) }
// Use them like this:
func a() {
defer untrace("a") //this defer will run when func a() 're finished.
trace("a")
defer untrace1("a") //this defer will run when func a() 're finished.
// do something....
}
func main() {
fmt.Println(morestrings.ReverseRunes("!oG ,olleH"))
a()
for i := 0; i < 5; i++ {
defer fmt.Printf("%d ", i) //this defer will run when func a() 're finished.
//和析构函数的顺序一样,先调用的后执行,从0开始1 2 3 4遍历,输出却是4 3 2 1 0
}
}