Golang中的 defer 关键字和Python中的上下文管理with关键字

发布于:2024-05-30 ⋅ 阅读:(116) ⋅ 点赞:(0)

defer,中文意思是:推迟

常用用于关闭文件操作,简而言之,就是try/finally的一种替代方案

使用示例

package main

import "fmt"

func main() {
    defer fmt.Println("执行延迟的函数")
    fmt.Println("执行外层函数")
}

执行结果

执行外层函数
执行延迟的函数

我们在代码中加入一个除零操作,引发异常

package main

import "fmt"

func main() {
    defer fmt.Println("执行延迟的函数")

    var a int = 0
    var b int = 2

    r := b / a

    fmt.Println("执行外层函数", r)
}

通过执行结果,可以看到:程序发生异常了,defer语句也是会执行的

执行延迟的函数
panic: runtime error: integer divide by zero

goroutine 1 [running]:
main.main()
    /Users/Desktop/main.go:11 +0x6c
exit status 2

和Python中的上下文管理with关键词很类似的功能

class Foo():
  def __enter__(self):
    print('__enter__')
    return self

  def __exit__(self, exc_type, exc_value, exc_tb):
    print('__exit__')

if __name__ == '__main__':
    with Foo() as foo:
        a = 1/0
        print('do something')
__enter__
__exit__
Traceback (most recent call last):
  File "/Users/Desktop/demo.py", line 11, in <module>
    a = 1/0
ZeroDivisionError: division by zero

Golang的文件读取操作

package main

import (
    "os"
)

func main() {
    file, _ := os.Open("demo.txt")
    defer file.Close()
    // do something
}

Python的文件读取

def main():
  with open('demo.txt', 'r') as f:
    pass


if __name__ == '__main__':
  main()

比较下来,发现:

  1. Python中通过上下文管理的概念来实现文件关闭操作;
  2. golang中没有引入新的概念,处理起来更为方便。

参考


网站公告

今日签到

点亮在社区的每一天
去签到