新聞中心
在Go語言中,可以使用關鍵字defer向函數(shù)注冊退出調用,即主函數(shù)退出時,defer后的函數(shù)才被調用。defer語句的作用是不管程序是否出現(xiàn)異常,均在函數(shù)退出時自動執(zhí)行相關代碼。

讓客戶滿意是我們工作的目標,不斷超越客戶的期望值來自于我們對這個行業(yè)的熱愛。我們立志把好的技術通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領域值得信任、有價值的長期合作伙伴,公司提供的服務項目有:主機域名、網站空間、營銷軟件、網站建設、望江網站維護、網站推廣。
但是,你還可以使用defer在任何函數(shù)開始后和結束前執(zhí)行配對的代碼。這個隱藏的功能在網上的教程和書籍中很少提到。要使用此功能,需要創(chuàng)建一個函數(shù)并使它本身返回另一個函數(shù),返回的函數(shù)將作為真正的延遲函數(shù)。在 defer 語句調用父函數(shù)后在其上添加額外的括號來延遲執(zhí)行返回的子函數(shù)如下所示:
func main() {
defer greet()()
fmt.Println("Some code here...")
}
func greet() func() {
fmt.Println("Hello!")
return func() { fmt.Println("Bye!") } // this will be deferred
}
輸出以下內容:
Hello!
Some code here...
Bye!
父函數(shù)返回的函數(shù)將是實際的延遲函數(shù)。父函數(shù)中的其他代碼將在函數(shù)開始時(由 defer 語句放置的位置決定)立即執(zhí)行。
這為開發(fā)者提供了什么能力?因為在函數(shù)內定義的匿名函數(shù)可以訪問完整的詞法環(huán)境(lexical environment),這意味著在函數(shù)中定義的內部函數(shù)可以引用該函數(shù)的變量。在下一個示例中看到的,參數(shù)變量在measure函數(shù)第一次執(zhí)行和其延遲執(zhí)行的子函數(shù)內都能訪問到:
func main() {
example()
otherExample()
}
func example(){
defer measure("example")()
fmt.Println("Some code here")
}
func otherExample(){
defer measure("otherExample")()
fmt.Println("Some other code here")
}
func measure(name string) func() {
start := time.Now()
fmt.Printf("Starting function %s\n", name)
return func(){ fmt.Printf("Exiting function %s after %s\n", name, time.Since(start)) }
}
輸出以下內容:
Starting example
Some code here
Exiting example after 0s
Starting otherExample
Some other code here
Exiting otherExample after 0s
此外函數(shù)命名的返回值也是函數(shù)內的局部變量,所以上面例子中的measure函數(shù)如果接收命名返回值作為參數(shù)的話,那么命名返回值在延遲執(zhí)行的函數(shù)中訪問到,這樣就能將measure函數(shù)改造成記錄入?yún)⒑头祷刂档墓ぞ吆瘮?shù)。
下面的示例是引用《go 語言程序設計》中的代碼段:
func bigSlowOperation() {
defer trace("bigSlowOperation")() // don't forget the extra parentheses // ...lots of work… time.Sleep(10 * time.Second) // simulate slow operation by sleeping } func trace(msg string) func() { start := time.Now() log.Printf("enter %s", msg) return func() { log.Printf("exit %s (%s)", msg,time.Since(start)) } }
可以想象,將代碼延遲在函數(shù)的入口和出口使用是非常有用的功能,尤其是在調試代碼的時候。
當前標題:Go語言中關鍵字defer使用方法
本文網址:http://www.5511xx.com/article/dpsjppj.html


咨詢
建站咨詢
