go defer用法_类似与python_java_finially

简介: 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)
}



相关文章
|
28天前
|
Python
python基本用法
【9月更文挑战第5天】python基本用法
38 7
|
5天前
|
Python
Python中正则表达式(re模块)用法详解
Python中正则表达式(re模块)用法详解
13 2
|
18天前
|
人工智能 数据挖掘 开发者
Python用法
Python用法
23 10
|
5天前
|
Python
Python变量用法——单下划线变量名_ 原创
Python变量用法——单下划线变量名_ 原创
15 0
|
5天前
|
Python
Python变量用法——变量解包
Python变量用法——变量解包
15 0
|
2月前
|
Python
Python 中 help() 和 dir() 函数的用法
【8月更文挑战第29天】
28 5
|
16天前
|
数据处理 开发者 Python
探索Python中的列表推导式在Python编程中,列表推导式是一种简洁而高效的方法,用于从现有的列表创建新列表。本文将深入探讨列表推导式的用法、优势以及一些实际应用示例。
列表推导式是Python提供的一种强大工具,它允许开发者以更简洁的语法快速生成列表。通过结合循环和条件语句,列表推导式能够简化代码结构,提高开发效率。本文详细介绍了列表推导式的基本用法,并通过实例展示了其在数据处理、转换和过滤中的广泛应用。
16 0
|
2月前
|
JSON 人工智能 Go
go 反射的常见用法
go 反射的常见用法
32 4
|
2月前
|
人工智能 编译器 Go
go slice 基本用法
go slice 基本用法
43 1
|
2月前
|
存储 Go
掌握 Go 语言的 defer 关键字
掌握 Go 语言的 defer 关键字
下一篇
无影云桌面