Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use defer in golang

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

This article is to share with you about how to use defer in golang. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

In golang, the defer code block adds a function call to the function call list. This function call is not a normal function call, but will add a function call after the function returns normally, that is, return. Therefore, defer is usually used to release internal variables of a function.

To better learn the behavior of defer, let's first look at the following code:

Func CopyFile (dstName, srcName string) (written int64, err error) {src, err: = os.Open (srcName) if err! = nil {return} dst, err: = os.Create (dstName) if err! = nil {return} written, err = io.Copy (dst, src) dst.Close () src.Close () return}

This code can be run, but there is a 'security risk'. If the call to dst, err: = os.Create (dstName) fails, the function exits by executing a return. However, the previously created src (file handle) is not released. The above code is simple, so we can see at a glance that there is a problem that the file has not been released. If our logic is complex or there are too many code calls, such errors may not be detected in time. This can be avoided by using defer. Here is the code that uses defer:

Func CopyFile (dstName, srcName string) (written int64, err error) {src, err: = os.Open (srcName) if err! = nil {return} defer src.Close () dst, err: = os.Create (dstName) if err! = nil {return} defer dst.Close () return io.Copy (dst, src)}

With defer, we can gracefully turn off / clean up the variables used in the code. Defer, as a golang cleanup variable, has its unique and explicit behavior. Here are three rules for the use of defer.

Once the rule defer is declared, its parameters will be parsed in real time.

We explain this rule with the following code:

Func a () {I: = 0defer fmt.Println (I) i++return}

As we said above, the defer function is called after return. So after the execution of this function, you don't have to output 1?

The reader compiles and sees by himself, the result output is 0. 0. Why?

This is because although we define a function with variables after defer: fmt.Println (I). But this variable (I) is determined by the time defer is declared. In other words, the above code is equivalent to the following code:

Func a () {I: = 0defer fmt.Println (0) / / because iTun0, tell golang explicitly to i++return the output 0 when the program exits.

To illustrate this more clearly, let's go on to define a defer:

Func a () {I: = 0defer fmt.Println (I) / / output 0, because I is 0i++defer fmt.Println (I) / / output 1, because I is 1return}

From the run result, you can see that the value of the defer output is the value at the time of definition. Rather than the value of the variable when the defer is actually executed (it's important, if it's not clear, it will result in inconsistent expected results)

But why output 1 first and then output 0? Look at rule number two below.

Rule 2 defer execution order is first in and then out

When multiple defer code blocks are defined at the same time, defer is called in the order in which the golang installation is defined and then executed. No matter why, that's how golang defines it. We use the following code to deepen our memory and understanding:

Func b () {for I: = 0; I < 4; iTunes + {defer fmt.Print (I)}}

In the loop, four blocks of defer code are defined in turn. Combined with rule one, we can clearly know what value each defer code block should output. Installation of the first-in-first-out principle, we can see that the output in turn 3210.

Rule 3: defer can read named return values.

Take a look at the following code first:

Func c () (I int) {defer func () {ionization +} () return 1}

The output is 12. At the beginning, we said that defer is executed after the return call. What needs to be clear here is that the scope of the defer code block is still within the function, combined with the above function, that is, the scope of defer is still within the c function. So defer can still read the variables in the c function (if you can't read the variables in the function, how to clear the variables.)

When return 1 is executed, the value of I is 1. At this point, the defer code block begins to execute, incrementing I. So output 2.

Having mastered the above three rules for using defer, we can clearly know the expected results of defer when we encounter a block of defer code.

The above is how to use defer in golang. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report