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 precalculation parameters in Golang

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you how to use the defer pre-calculation parameters in Golang. I hope you will get something after reading this article. Let's discuss it together.

What is defer?

Defer is used to declare a delay function, put this function on a stack, and when the outer contains the method return, returns the parameter to be called before the method is called, or when it runs to the outermost method body "}". We often use him to release resources, such as shutting down io operations.

Func doSomething (fileName string) {file,err: = os.Open (fileName) if err! = nil {panic (err)} defer file.Close ()}

Defer ensures that the method can be called before the peripheral function returns. It's kind of like try finally in other words.

Try {} finally {} Go language defer precomputation parameters

All function calls in the Go language are value-passing, and although defer is a keyword, it also inherits this feature. Suppose we want to calculate the running time of the main function, we might write the following code:

Package mainimport ("fmt"time") func main () {startedAt: = time.Now () defer fmt.Println (time.Since (startedAt)) time.Sleep (time.Second) / / dormancy for one second}

The result is:

D:\ workspace\ go\ src\ test > go run main.go

0s

The running results do not meet our expectations. What is the reason behind this phenomenon? After analysis, we will find that calling the defer keyword will immediately copy the external parameters referenced in the function, so the result of time.Since (startedAt) is not calculated before the main function exits, but [when the defer is stacked] when the defer keyword is called, resulting in the output of the above code 0s

Let's look at a simple example to illustrate the above explanation:

Package mainimport ("fmt") func main () {I: = 1 defer fmt.Println (test (I)) I = 100} func test (I int) int {I = I + 1 return I} D:\ workspace\ go\ src\ test > go run main.go2

When the code runs to defer fmt.Println (test (I)), the parameters of the outermost function on the right side of defer are calculated and passed into the function, but the code of the function body is not executed until the function that wraps defer returns. We first see that the parameters of the outermost function on the right side of defer will be calculated and passed into the function, the corresponding example is to calculate test (I) first, then calculate test (1) to get 2, and then fmt.Println (2) into the stack, wait until the final program is finished, and then run defer the result is 2 (but will not execute the code of the function body until the function wrapping defer returns).

Let's look at another example of combining anonymous functions:

Package mainimport ("fmt") func main () {I: = 1 defer func () {fmt.Println (test (I))} () I = 100} func test (I int) int {I = I + 1 return I}

Results:

D:\ workspace\ go\ src\ test > go run main.go

one hundred and one

Using anonymous functions, the result is 101, which is equivalent to I giving 100 to the test method, so why? The same sentence: but the code for the body of the function will not be executed until the function that wraps defer returns

In other words, he will put the whole {fmt.Println (test (I))} () function on the stack, and wait until the program finishes running, and then run defer. At this time, I is 100. after running test, it is 101.

So if you want to solve the first problem of printing as 0s, you can use an anonymous function to solve it, as follows:

Package mainimport ("fmt"time") func main () {startedAt: = time.Now () defer func () {fmt.Println (time.Since (startedAt))} () time.Sleep (time.Second) / / dormancy for one second}

Results:

D:\ workspace\ go\ src\ test > go run main.go

1.0152825s

After reading this article, I believe you have a certain understanding of "how to use defer precalculation parameters in Golang". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

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

Development

Wechat

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

12
Report