官术网_书友最值得收藏!

Defer

By deferring a function, it will run whenever the current function is exited. This is a convenient way to ensure that a function will get executed before exiting, which is useful for cleaning up or closing files. It is convenient because a deferred function will get executed no matter where the surrounding function exits if there are multiple return locations.

Common use cases are deferring calls to close a file or database connection. Right after opening a file, you can defer a call to close. This will ensure that a file is closed whenever the function is exited, even if there are multiple return statements and you can't be sure about when and where the current function will exit.

This example demonstrates a simple use case for the defer keyword. It creates a file and then defers a call to file.Close():

package main

import (
"log"
"os"
)

func main() {

file, err := os.Create("test.txt")
if err != nil {
log.Fatal("Error creating file.")
}
defer file.Close()
// It is important to defer after checking the errors.
// You can't call Close() on a nil object
// if the open failed.

// ...perform some other actions here...

// file.Close() will be called before final exit
}

Be sure to properly check and handle errors. The defer call will panic if using a nil pointer.

It is also important to understand that deferred functions are run when the surrounding function is exited. If you put a defer call inside a for loop, it will not get called at the end of each for loop iteration.

主站蜘蛛池模板: 蓬安县| 乐东| 安顺市| 长顺县| 壶关县| 兰考县| 荔浦县| 清水河县| 南平市| 尖扎县| 鄂伦春自治旗| 龙江县| 葫芦岛市| 府谷县| 磐石市| 阿拉善盟| 桑植县| 清镇市| 铁力市| 团风县| 罗平县| 前郭尔| 卢氏县| 松原市| 泊头市| 贵定县| 丰县| 榆中县| 饶平县| 盐山县| 炉霍县| 清河县| 东乌| 阳春市| 克山县| 富蕴县| 双桥区| 额尔古纳市| 石景山区| 驻马店市| 昂仁县|