Diagram of deferred call defer in Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. > This tutorial will explain the use of **defer** in the Go language with a few practical examples. # What is defer? Modify a function by using ' defer ' to make it in an external function ["After Return"] (https://medium.com/@inanc/ yeah-semantically-after-is-the-right-word-fad1d5181891) is executed, even if the external function returns a [panic exception] (https://golang.org/ref/spec# Handling_panics), such functions are called ' Deferred call functions '. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-defer-simplified/what_is_defer.png) [Run code Online] (Https://play.golang.org/p/pSo9t5IJnM) _ Print: "First" then "later" _---* Go language does not require destructors because they do not have their own constructors, which is a good trade-offs. The ' defer ' statement is similar to ' finally ', but the difference between the two is that the scope of ' finally ' is in its * * Exception block * *, and the scope of ' defer ' is limited to the function that surrounds it. ---* * More about defer:** If you're curious about how the ' defer ' internal mechanism works, check out [my comments] (https://medium.com/@inanc/ yeah-semantically-after-is-the-right-word-fad1d5181891). Although it is always described in [official documents] (Https://blog.golang.org/defer-panic-and-recover) as "executed after an external function is returned," There are still some unknown details that have not been clarified. ---# # # # # # # # # # # # # # # Defer Common uses # # # Release A resource that has been made use the ' defer ' delay call function is often used to release acquired resources in the function body. [] (HTTPS://RAW.GITHUBUSERCONTENT.COM/STUDYGOLANG/GCTT-IMAGES/MASTER/GOLANG-DEFER-SIMPLIFIED/Releasing_acquired_resources.png) [Online Run code] (HTTPS://PLAY.GOLANG.ORG/P/Q4P6V_KIAX) This delay function closes the file handle that has already been opened, regardless of ' Newfromfile ' function returned an error. # # # Recover from Panic if **defer** and triggered [**panic**] (https://golang.org/ref/spec#Run_time_panics) are in the same **goroutine**, * * defer** enables the program to recover from the **panic**, avoiding the entire program from terminating. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-defer-simplified/save_us_from_ panic.png) [Online Run code] (https://play.golang.org/p/jJX-F3AOOy) where the ' Recover () ' function can return the arguments of the ' panic () ' function, which allows us to handle the **panic* on our own * At the same time you can also pass an error or other type of value to ' panic ' to determine what value is being thrown **panic**. [More details] (Https://blog.golang.org/defer-panic-and-recover) # # # delay closure A delay call function that uses ' defer ' can be any type of function, so when ' defer ' acts on an anonymous function, This function is able to get the latest state of the variables in the peripheral function body. It is worth noting that the following example shows that the anonymous function of a deferred call can get the final state of the local variable ' num '. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-defer-simplified/defered_ closure.png) [Online Run code] (https://play.golang.org/p/O16b0nDV7f) _ Understand how the defer function treats its context _### parameters instant Evaluation Go The runtime saves any arguments passed to the deferred call function when the function declaration is deferred, rather than when it is run. Example of---# # #In the following example, we define a delay closure that uses the variable ' n ' above with the same name and attempts to pass the ' I ' variable into the delay function again to increase the value of the variable ' n '. "' Gofunc count (i int) (n int) {defer func (i int) {n = n + i} (i) i = i * 2 n = i return}" ' We run this function to see "' Gocount (10)//Lose Out: 30 "* * what happened? **! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-defer-simplified/params_ Evaluation.png) _ Analyze visualization numbers (on the left): 1, 2, 3. _[online Run code] (HTTPS://PLAY.GOLANG.ORG/P/ZGEED9A1PR) * Translator Note: You can find the ' i ' variable of the passed-in delay function in the ' COUNT () ' Returns a copy value (that is, 10) that was recorded before it was run, even if the ' I ' variable used in the closure after the ' count () ' Return is still the previous copy value. Therefore, the 3rd step I should be 10, not 20, should be the author of a clerical error. *---The above example shows that by specifying the return value variable name, **defer** can also help us change the result of the return value before the function returns. # # # Delay calls multiple functions if there are multiple delay functions, they will be stored in a ' stack ', so the function that was finally modified by ' defer ' will be executed first after the function body returns. * Note: Using multiple ' defer ' expressions at the same time may reduce the readability of your code as shown in:! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-defer-simplified/multiple_ defers.png) output as follows ' Firstlast ' [Online Run code] (https://play.golang.org/p/aNNVV9DvXf) _ Understand how multiple defer work _** see how it works **! [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-defer-simplified/wAtch_how_it_works.gif) # # # Delay method of invoking an object you can also use ' defer ' to modify the object's methods. But there is another mystery, see Example # # # # # # # # # # # # # # # # # # # # # # Gotype car struct {model string}func (c car) Printmodel () {fmt. Println (C.model)}func main () {c: = Car{model: "DeLorean DMC-12"} Defer C.printmodel () C.model = "Chevrolet Impala"} "output knot "DeLorean DMC-12" # # # # # # # # # # # # # # # # # # Use pointer object as Receiver ' Gofunc (c *car) Printmodel () {fmt. Println (C.model)} ' ' Output is as follows ' ' Chevrolet Impala ' # # # # # # # # # # # # # # # # # # # # # #! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-defer-simplified/what_is_going_ On.png) We need to remember that when the peripheral function is not returned, the runtime of Go will immediately save the arguments passed to the delay function. Thus, when a method with a value as a receiver is **defer** modified, the receiver is copied at the time of declaration (in this case the *car* object), and any modifications to the copy are not visible (*car.model* in the example), because the receiver is also the input parameter. The value of the parameter (that is, "DeLorean DMC-12") is immediately derived when using the **defer** adornment. In another case, when the call is deferred, the recipient is a pointer object, and although a new pointer variable is generated, it points to the same address as the "C" pointer in the previous example. As a result, any modification will work perfectly in the same object. [Run code Online] (Https://play.golang.org/p/XNQ7gD6zgG)

Via:https://blog.learngoprogramming.com/golang-defer-simplified-77d3b2b817ff

Author: inanc Gumus Translator: yujiahaol68 proofreading: Rxcai polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

1484 reads ∙1 likes
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.