defer先进后出
举例:
package main
import (
"fmt"
"os"
"bufio"
)
//打开文件
func writeFile(filename string) {
file, err := os.Create(filename)
if err != nil {
panic(err)
}
//往文件写内容(直接写文件会比较慢,所以这里用bufio。先写到内存里,再内存一下写进去会比较快)
writer := bufio.NewWriter(file)
for i := 0; i < 20; i++ {
fmt.Fprintln(writer, i)
}
defer file.Close()
defer writer.Flush()
}
func main() {
//tryDefer()
writeFile("haha.txt")
}
先执行writer.Flush(),再执行file.Close()。反之不能写入