search
HomeBackend DevelopmentGolangUse eight demos to understand the five major features of Go language defer

Using the defer keyword in Go language can delay code execution until the end of the function. In development, we often use the defer keyword to complete the aftermath work, such as closing open file descriptors, closing connections, and releasing resources.

func demo0() {
    fileName := "./test.txt"
    f, _ := os.OpenFile(fileName, os.O_RDONLY, 0)
    defer f.Close()

    contents, _ := ioutil.ReadAll(f)
    fmt.Println(string(contents))}

deferThe keyword usually follows immediately after the resource opening code to prevent subsequent forgetting to release the resource. The code declared by defer will not actually be executed until the end of the function. Although defer is simple and easy to use, but if you ignore its features, you will face confusion during development . Therefore, I summarized the five major features of defer and gradually introduced the features of defer through 8 demos.

Feature 1: Calling order when multiple defers are used: first in, last out

When multiple defer keywords are used, the defer statement declared first is called later. Similar to the "stack" first-in-last-out feature, this feature of defer is also easy to understand. Resources opened by first may be relied upon by subsequent code, so ## It is safe to release after #.

func demo1() {
    for i := 0; i Feature 2: The scope is the current function, and there are different defer stacks under different functions<h2></h2>Run demo2. It can be seen from the results that the first anonymous function and the second anonymous function The order of defer execution of functions does not matter. <p>The defer scope is only the current function and is executed at the end of the current function, so there are different defer stacks under different functions. <br></p><pre class="brush:php;toolbar:false">func demo2() {
    func() {
        defer fmt.Println(1)
        defer fmt.Println(2)
    }()

    fmt.Println("=== 新生代农民工啊 ===")

    func() {
        defer fmt.Println("a")
        defer fmt.Println("b")
    }()}// 2// 1// === 新生代农民工啊 ===// b// a
Run demo3_1, according to the results, we can conclude: defer in

The value of the formal parameter n has been confirmed when is declared, not when is executed; therefore, no matter how the subsequent variable num changes, it will not affect the output result of defer.

func demo3_1() {
    num := 0
    defer func(n int) {
        fmt.Println("defer:", n)
    }(num)
    // 等同 defer fmt.Println("defer:", num)

    for i := 0; i Run demo3_2, why is the final output result of defer here the same as the variable num? Because pointers are used here. <p>defer <br>When declaring<strong>, the address pointed by the formal parameter p pointer has been confirmed, pointing to the variable num; subsequently the variable num changes. So when defer </strong> is executed<strong>, the output is the current value of the variable num pointed to by the p pointer. </strong></p><pre class="brush:php;toolbar:false">func demo3_2() {
    num := 0
    p := &num    defer func(p *int) {
        fmt.Println("defer:", *p)
    }(p)

    for i := 0; i Look at demo3_3 again. The variables printed by defer are not passed in through function parameters. The "global variable" num is only obtained when defer<p> is executed, so the output result of defer is the same as the variable. num is consistent. <strong><pre class="brush:php;toolbar:false">func demo3_3() {
    num := 0
    defer func() {
        fmt.Println("defer:", num)
    }()

    for i := 0; i 
Feature 4: return and defer execution order: return first defer then

Run demo4_1, you can find that defer and return are executed at the end of the function, but return is executed before defer;

func demo4_1() (int, error) {
    defer fmt.Println("defer")
    return fmt.Println("return")}// return// defer

This is obvious from the output results

, but when the execution order of return and defer and the

**function return value** "meet", Many complex scenarios will result. In demo4_2, the function uses to name the return value
, and the final output result is 7. It has gone through the following processes:

    (First) the variable num is used as the return value, and the initial value is 0;
  1. (Second) Then The variable num is assigned a value of 10;
  2. (Then) when return, the variable num is reassigned a value of 2 as the return value;

  3. (Then) defer is executed after return, and the variable num is obtained for modification, and the value is 7;
  4. (Finally) the variable num is used as the return value, and the final function return result is 7;
  5. func demo4_2() (num int) {
     num = 10
     defer func() {
         num += 5
     }()
    
     return 2}// 7

  6. Let’s look at another example.
In demo4_3, the function uses

anonymous return value
, and the final result output is 2. The process is as follows:

    Enters the function, and the return value variable is not created at this time;
  1. creates the variable num and assigns the value to 10; When
  2. return, create a function return value variable and assign it a value of 2; you can regard this return value variable as an anonymous variable, or as a, b, c, or d variable ..., but it is not the variable num;
  3. defer, no matter how you modify the variable num, it has nothing to do with the function return value;
  4. Therefore, the final function return result is 2;
  5. func demo4_3() int {
     num := 10
     defer func() {
         num += 5
     }()
    
     return 2}// 2

    Feature 5: When panic occurs, the declared defer will pop out of the stack and execute

    Run demo5_1, you can see that when panic occurs, Trigger the declared defer to pop out of the stack and then panic. However, the defer declared after the panic will not be executed.

    func demo5_1() {
     defer fmt.Println(1)
     defer fmt.Println(2)
     defer fmt.Println(3)
    
     panic("没点赞异常") // 触发defer出栈执行
    
     defer fmt.Println(4) // 得不到执行}

    It is precisely by using this feature that panic can be captured through recover in defer to prevent the program from crashing.

    func demo5_2() {
     defer func() {
         if err := recover(); err != nil {
             fmt.Println(err, "问题不大")
         }
     }()
    
     panic("没点赞异常") // 触发defer出栈执行
    
     // ...}

    Attached

    Full code:

    github.com/newbugcoder/learngo/tre...

The above is the detailed content of Use eight demos to understand the five major features of Go language defer. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Mastering Go Strings: A Deep Dive into the 'strings' PackageMastering Go Strings: A Deep Dive into the 'strings' PackageMay 12, 2025 am 12:05 AM

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

'encoding/binary' Package in Go: Your Go-To for Binary Operations'encoding/binary' Package in Go: Your Go-To for Binary OperationsMay 12, 2025 am 12:03 AM

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Go Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageGo Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageMay 12, 2025 am 12:02 AM

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.

How do you use the 'strings' package to manipulate strings in Go?How do you use the 'strings' package to manipulate strings in Go?May 12, 2025 am 12:01 AM

You can use the "strings" package in Go to manipulate strings. 1) Use strings.TrimSpace to remove whitespace characters at both ends of the string. 2) Use strings.Split to split the string into slices according to the specified delimiter. 3) Merge string slices into one string through strings.Join. 4) Use strings.Contains to check whether the string contains a specific substring. 5) Use strings.ReplaceAll to perform global replacement. Pay attention to performance and potential pitfalls when using it.

How to use the 'bytes' package to manipulate byte slices in Go (step by step)How to use the 'bytes' package to manipulate byte slices in Go (step by step)May 12, 2025 am 12:01 AM

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

GO bytes package: What are the alternatives?GO bytes package: What are the alternatives?May 11, 2025 am 12:11 AM

ThealternativestoGo'sbytespackageincludethestringspackage,bufiopackage,andcustomstructs.1)Thestringspackagecanbeusedforbytemanipulationbyconvertingbytestostringsandback.2)Thebufiopackageisidealforhandlinglargestreamsofbytedataefficiently.3)Customstru

Manipulating Byte Slices in Go: The Power of the 'bytes' PackageManipulating Byte Slices in Go: The Power of the 'bytes' PackageMay 11, 2025 am 12:09 AM

The"bytes"packageinGoisessentialforefficientlymanipulatingbyteslices,crucialforbinarydata,networkprotocols,andfileI/O.ItoffersfunctionslikeIndexforsearching,Bufferforhandlinglargedatasets,Readerforsimulatingstreamreading,andJoinforefficient

Go Strings Package: A Comprehensive Guide to String ManipulationGo Strings Package: A Comprehensive Guide to String ManipulationMay 11, 2025 am 12:08 AM

Go'sstringspackageiscrucialforefficientstringmanipulation,offeringtoolslikestrings.Split(),strings.Join(),strings.ReplaceAll(),andstrings.Contains().1)strings.Split()dividesastringintosubstrings;2)strings.Join()combinesslicesintoastring;3)strings.Rep

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools