1 Star 0 Fork 0

c01dface/s-go-example

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
defer.go 983 Bytes
一键复制 编辑 原始数据 按行查看 历史
c01dface 提交于 2024-12-11 19:08 . add defer.go
package main
// defer is used to ensure that a function call is performed later in
// a program's execution, usually for purposes of cleanup.
import (
"fmt"
"os"
)
func main() {
// Suppose we wanted to create a file, write to it, and then close
// when we're done. Here's how we could do that with defer.
// Immediately after getting a file object with createFile, we defer
// the closing of that file with closeFile. This will be executed at
// the end of the enclosing function(main), after writeFile has finished.
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)
}
func createFile(p string) *os.File {
fmt.Println("creating file", p)
f, err := os.Create(p)
if err != nil {
panic(err)
}
return f
}
func closeFile(f *os.File) {
fmt.Println("closing file")
err := f.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func writeFile(f *os.File) {
fmt.Println("writing file")
fmt.Fprintln(f, "data")
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/vmalloc/s-go-example.git
git@gitee.com:vmalloc/s-go-example.git
vmalloc
s-go-example
s-go-example
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385