Go实例: Defer

Shanon ·
更新时间:2024-11-10
· 1014 次阅读

package main import ( "fmt" "os" ) func main() { f := createFile("/tmp/defer.txt") defer closeFile(f) writeFile(f) } func createFile(p string) *os.File { fmt.Println("creating") f, err := os.Create(p) if err != nil { panic(err) } return f } func writeFile(f *os.File) { fmt.Println("writing") fmt.Fprintln(f, "data") } func closeFile(f *os.File) { fmt.Println("closing") err := f.Close() if err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } }$ go run defer.go creating writing closing



GO实例 GO defer

需要 登录 后方可回复, 如果你还没有账号请 注册新账号