标签:pre text 过程 必须 重点 翻译 析构 应该 defer
1 // Contents returns the file‘s contents as a string. 2 func Contents(filename string) (string, error) { 3 f, err := os.Open(filename) 4 if err != nil { 5 return "", err 6 } 7 defer f.Close() // f.Close will run when we‘re finished. 8 9 var result []byte 10 buf := make([]byte, 100) 11 for { 12 n, err := f.Read(buf[0:]) 13 result = append(result, buf[0:n]...) // append is discussed later. 14 if err != nil { 15 if err == io.EOF { 16 break 17 } 18 return "", err // f will be closed if we return here. 19 } 20 } 21 return string(result), nil // f will be closed if we return here. 22 }
func trace(s string) string { fmt.Println("entering:", s) return s } func un(s string) { fmt.Println("leaving:", s) } func a() { defer un(trace("a")) fmt.Println("in a") } func b() { defer un(trace("b")) fmt.Println("in b") a() } func main() { b() }
entering: b in b entering: a in a leaving: a leaving: b
1 for i := 0; i < 5; i++ { 2 defer fmt.Printf("%d ", i) 3 }
defer的函数调用按着后进先出(LIFO)的方式执行。大概猜一猜,每次defer都会将函数调用压入栈中,最后依次出栈执行。
标签:pre text 过程 必须 重点 翻译 析构 应该 defer
原文地址:https://www.cnblogs.com/chyuwei/p/11082225.html