package main

import (
	"bufio"
	"fmt"
	"learngo/functional/fib"
	"os"
)

/*

1、 确保调用在函数结束时发生

2、 参数在defer语句时计算

3、defer 列表为后进行出

*/

func tryDefer() {
	defer fmt.Println(1)
	defer fmt.Println(2)
	fmt.Println(3)

	for i := 0; i < 100; i++ {
		defer fmt.Println(i)
		if i == 30 {
			panic(" printed too many ")
		}
	}

}

func writeFile(filename string) {
	// 打开一个文件
	//file, err := os.Create(filename)
	file, err := os.OpenFile(filename, os.O_EXCL|os.O_CREATE, 0666)

	// 自定义error

	//err = errors.New(" this is a custom error !")

	fmt.Printf(" open file error %s  \n :", err)

	//异常处理
	if err != nil {

		if pathError, ok := err.(*os.PathError); !ok {
			panic(err)
		} else {
			fmt.Printf("%s,  %s,  %s \n",
				pathError.Op,
				pathError.Path,
				pathError.Err,
			)
		}
		return
	}
	//关闭文件
	defer file.Close()

	writer := bufio.NewWriter(file)
	// 写入文件
	defer writer.Flush()

	f := fib.Fibonacci()
	for i := 0; i < 20; i++ {
		fmt.Fprintln(writer, f())
	}
}

func main() {
	writeFile("fib1.txt")
	//tryDefer()
}
