首页 > 其他分享 >[Go] Defer keyword

[Go] Defer keyword

时间:2024-02-06 09:16:02浏览次数:28  
标签:function Defer return keyword err defer nil file Go

defermake sure the operation will be executed at the end of a function.

func loadChampions() ([]champion, error) {
	file, err := os.Open("tft_champions.json")
	if err != nil {
		return nil, err
	}

	defer file.Close()

	var champions []champion
	for {
		if err := json.NewDecoder(file).Decode(&champions); err == io.EOF {
			break
		} else if err != nil {
			return nil, err
		}
	}

	return champions, nil
}

 

Notice that even we write defer file.Close() after os.Open, it doesn't mean it will close the file right away, file will be close by the end of the function.

 

Key Points about defer:

  • Resource Management: It's a best practice to use defer for closing files, network connections, or releasing other resources. This pattern helps prevent resource leaks, which can lead to performance issues or crashes due to exhausted resources.

  • Order of Execution: If multiple defer statements are called within the same function, they are executed in the reverse order they were deferred. This LIFO (Last In, First Out) execution order is particularly useful when the order of operations for cleanup is important.

  • Error Handling and Cleanup: In functions with complex error handling and multiple return points, defer ensures that cleanup actions are performed without needing to duplicate cleanup code before each return statement.

  • Deferred Function Arguments: The arguments of a deferred function are evaluated when the defer statement is executed, not when the deferred function is actually called. This is an important distinction when deferring a call with arguments that may change later in the function.

  • Panic Recovery: defer can also be used in conjunction with recovery from panics (unexpected errors), allowing a program to recover from an error state gracefully or to perform necessary cleanup before crashing.

标签:function,Defer,return,keyword,err,defer,nil,file,Go
From: https://www.cnblogs.com/Answer1215/p/18009084

相关文章

  • [Go] defer & recover
    PanicrecoveryisamechanisminGothatallowsaprogramtohandleunexpectederrors(panics)gracefully. packagemainimport( "fmt")funcmayPanic(){ //Thisfunctionsimulatesasituationthatcausesapanic. //Forexample,adivisi......
  • [Go - slice] Remove Elements from a slice in Go
    Gohasaspecialindexingsyntaxthatformsthebasisofremovingoneormoreelementsfromaslice.Iwillteachyouthissyntaxandshowyouitsvariousforms.Baseduponthat,I'llshowyouhowtoremoveasingleelementfromaslice.However,you......
  • 2月摸鱼计划03 从并发编程本质了解Go高性能的本质
    1.0从并发编程本质了解Go高性能的本质1.1Goroutine协程可以理解为轻量级线程;Go更适合高并发场景原因之一:Go语言一次可以创建上万协成;“快速”:开多个协成打印。gofunc():在函数前加go代表创建协程;time.Sleep():协程阻塞,使主协程在子协程结束前阻塞不退出;乱序输出说......
  • client-go http trace分析耗时
    klog.InitFlags(nil)flag.Parse()deferklog.Flush()cfg,err:=clientcmd.BuildConfigFromFlags("","/root/.kube/config")iferr!=nil{ klog.Fatalf("Errorbuildingkubeconfig:%s",err.Error())}kubeClient,err:=kubern......
  • [转][Centos]安装 gogs
    也可以从https://gogs.io下载安装参考:https://blog.csdn.net/hahofe/article/details/1172919201、包管理安装#获取安装源sudowget-O/etc/yum.repos.d/gogs.repohttps://dl.packager.io/srv/gogs/gogs/main/installer/el/7.repo#开始下载安装sudoyuminstallgogs......
  • 在我的VS2019中重新配置2017项目生成的google test 项目
    原来的项目是其他版本的VS配置的,自己下载下来时候,本机也没有装GoogleTest所以用不起。如果重建项目在一个个引入工程代码太麻烦(文件多),所以我就想着有没有什么办法快捷配置,不用重建工程以下是我的一个配置方法,供大家交流学习:1.首先你本机要安装上GoogleTest,安装方法自查;2.如......
  • MongoDB配置用户账号与访问控制
    1.admin库创建root角色权限的用户db.createUser({user:"root",pwd:"123qwe",roles:["root"]})2.修改mongo配置文件,开启用户名密码连接验证security:authorization:enabled3.cmd关闭mongo服务netstopMongoDB4.cmd启动mongo服务netstartMongoDB直接localhost连接......
  • go 项目构建
    Go准备依赖环境:golang参考官网地址:https://golang.google.cn/dl/开发工具:可使用jetbrian的Go,但是需要付费,免费也就30天试用,没有社区版。Idea安装Go-plugin插件。插件地址:https://plugins.jetbrains.com/plugin/9568-go/versions/stable以Module形式导入应用因Go项目......
  • go-carbon v2.3.8 发布,轻量级、语义化、对开发者友好的 golang 时间处理库
    carbon是一个轻量级、语义化、对开发者友好的golang时间处理库,支持链式调用。目前已被awesome-go收录,如果您觉得不错,请给个star吧github.com/golang-module/carbongitee.com/golang-module/carbon安装使用Golang版本大于等于1.16//使用github库goget-ugithu......
  • go dns解析参数配置
    //lookup_dns.gopackagemainimport( "net" "time" "k8s.io/klog/v2")funcmain(){ dns:="kubernetes.default" if_,err:=net.LookupHost(dns);err!=nil{ klog.Errorf("lookup%sfailed,erris%v......