兄弟連Go語言培訓帶你實戰GO案例(7)Go Defer
來源:互聯網
上載者:User
兄弟連Go語言培訓課程體系設計架構包括了區塊鏈的基礎語言Go語言、區塊鏈後端技術體系、區塊鏈公鏈、區塊鏈分布式應用開發等內容講解,以及到最後的面試指導和項目實戰。課程由清華微軟Google名師團隊精心打造,曆時半年時間共同研發而出。 GoDefer Defer用來保證一個函數調用會在程式執行的最後被調用。通常用於資源清理工作。packagemain import"fmt" import"os" //假設我們想建立一個檔案,然後寫入資料,最後關閉檔案 funcmain(){ //在使用createFile得到一個檔案對象之後,我們使用defer //來調用關閉檔案的方法closeFile,這個方法將在main函數 //最後被執行,也就是writeFile完成之後 f:=createFile("/tmp/defer.txt") //Windows下面使用這個語句 //f:=createFile("D:\\Temp\\defer.txt") defercloseFile(f) writeFile(f) } funccreateFile(pstring)*os.File{ fmt.Println("creating") f,err:=os.Create(p) iferr!=nil{ panic(err) } returnf } funcwriteFile(f*os.File){ fmt.Println("writing") fmt.Fprintln(f,"data") } funccloseFile(f*os.File){ fmt.Println("closing") f.Close() } 運行結果 creating writing closing 使用defer來調用closeFile函數可以保證在main函數結束之前,關閉檔案的操作一定會被執行。210 次點擊