go defer用法_类似与python_java_finially

defer 执行 时间

defer 一般 定义在 函数 开头, 但是 他会 最后 被执行

A defer statement defers the execution of a function until the surrounding function returns.

如果说 为什么 不在 末尾 定义 defer 呢, 因为 当 错误 发生时, 程序 执行 不到 末尾 就会 崩溃.

defer 的 参数 定义 会 立刻 被执行, 最后 被执行 的 只有 最外层 函数的 定义.

The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

下边 的 例子 需要好好 理解,
会最后 被执行的 , 只有 最外层的 函数调用

第二层的 函数 作为 参数 传入 时, 也会被 立即 执行.

defer 中的 变量, 会立即 保存 当前 状态,
比如 x:=1 ; defer print(x); x=2 , 只会 输出 1

defer 是 stack 类型的 顺序, 先入后出

先定义 的 defer 会 最后被执行

理解 defer 执行 时机

defer 执行 还是 比较有特色的, 需要 特殊记忆

package main

import "fmt"

func main() {
	defer fmt.Println("world1")
	defer fmt.Println(fmt.Println("world2"))

	fmt.Println("hello")
	return fmt.Println("finally")
}
# output:
world2
hello
7 <nil>
world1

defer 用与 关闭文件


func CopyFile(dstName, srcName string) (written int64, err error) {
    src, err := os.Open(srcName)
    if err != nil {
        return
    }
    defer src.Close()

    dst, err := os.Create(dstName)
    if err != nil {
        return
    }
    defer dst.Close()

    return io.Copy(dst, src)
}