Go プログラミング例 [遅延呼び出しを延期する]

目次を読む

Defer は、プログラムの実行が終了する前に関数呼び出しが確実に実行されるようにするために使用されます。

一部の清掃作業にも使用されます。

ensuredefer は、と が他の言語と同様finallyに使用される場所で使用されます。

// defer.go
package main

import (
	"fmt"
	"os"
)

// 假设我们想要创建一个文件,向它进行写操作,然后在结束时关闭它。
// 这里展示了如何通过 `defer` 来做到这一切。
func main() {
    
    

	// 在 `createFile` 后得到一个文件对象,
	// 我们使用 defer 通过 `closeFile` 来关闭这个文件。
	// 这会在封闭函数(`main`)结束时执行,就是 `writeFile` 结束后。
	f := createFile("/tmp/defer.txt")
	defer closeFile(f)
	writeFile(f)
}

func createFile(p string) *os.File {
    
    
	fmt.Println("creating")
	f, err := os.Create(p)
	if err != nil {
    
    
		panic(err)
	}
	return f
}

func writeFile(f *os.File) {
    
    
	fmt.Println("writing")
	fmt.Fprintln(f, "data")
}

func closeFile(f *os.File) {
    
    
	fmt.Println("closing")
	f.Close()
}

[root@localhost test]# go run hello.go 
creating
writing
closing
[root@localhost test]# 
[root@localhost tmp]# ls -al | grep defer.txt
-rw-r--r--.  1 root                root                     5 3月  26 11:05 defer.txt
[root@localhost tmp]# cat defer.txt 
data
[root@localhost tmp]# 

おすすめ

転載: blog.csdn.net/weiguang102/article/details/129776978