search
HomeBackend DevelopmentGolangPassing pointer to go defer function doesn't work

将指针传递给 go defer 函数不起作用

In PHP programming, the pointer may not work when passed to the go defer function. Pointers in PHP are used to store the memory address of variables. By passing the pointer, the value of the original variable can be modified inside the function. However, when passing a pointer to a go defer function, it sometimes happens that the original variable cannot be modified. This may be because the go defer function creates a new Goroutine when executed, and the pointer may point to a different memory space, resulting in the failure to modify the value of the variable correctly. Therefore, in PHP programming, pointers should be passed to go defer functions with caution to avoid unexpected problems.

Question content

In my code, I try to use numaddr to record the changes in num after the defer statement

func deferrun() {
    num := 1
    numaddr := &num
    defer fmt.printf("num is %d", *numaddr)
    num = 2
    return
}

func main() {
    deferrun()
}

But I get num is 1 instead of 2, why does the defer function use the value of *numaddr instead of the address?

Then let me try another method

func deferRun() {
    num := 1
    numAddr := &num
    defer func(intAddr *int){
        fmt.Printf("num is %d", *numAddr)
    }(numAddr)
    
    num = 2
    fmt.Println("num is", *numAddr)
    return
}

func main() {
    deferRun()
}

This time it worked, I got num was 2, so I thought maybe defer fmt.printf(something) stored the string immediately when declaring it, and Isn't numaddr used when the defer function actually runs?

Solution

Interesting question. To answer this question, you must know a rule, like this go tutorial https://go.dev/tour/flowcontrol/12

The parameters of a delayed call are evaluated immediately, but the function call is not executed until the surrounding function returns. .

Example 1: Tell the defer function to print the value located at the specified memory address.

func deferrun() {
    num := 1
    numaddr := &num //address of variable num in stack memory, 0xc000076f38 for example
    defer func(intaddr *int){
        fmt.printf("num is %d", *numaddr)
    }(numaddr) //hey go, when the surrounding function returns, print the value located in this address (numaddr=0xc000076f38)
    num = 2 //now the value located in address 0xc000076f38 is 2
    return  
}

The output will be 2.

Example 2: Tell the defer function to print the specified value.

func deferRun() {
    num := 1
    numAddr := &num //address of variable num in stack memory, 0xc000076f38 for example
    defer fmt.Printf("num is %d", *numAddr) //Hey Go, when the surrounding function returns, print the this value *numAddr (*numAddr is 1 for now)
    num = 2 //Now the value located in address 0xc000076f38 is 2 but you told the defer function to print 1 before
    return  
}

The output will be 1.

The above is the detailed content of Passing pointer to go defer function doesn't work. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
How do I write mock objects and stubs for testing in Go?How do I write mock objects and stubs for testing in Go?Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How can I define custom type constraints for generics in Go?How can I define custom type constraints for generics in Go?Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

How do you write unit tests in Go?How do you write unit tests in Go?Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How can I use tracing tools to understand the execution flow of my Go applications?How can I use tracing tools to understand the execution flow of my Go applications?Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

How do you use the pprof tool to analyze Go performance?How do you use the pprof tool to analyze Go performance?Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications?Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications?Mar 25, 2025 am 11:17 AM

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

How do you use table-driven tests in Go?How do you use table-driven tests in Go?Mar 21, 2025 pm 06:35 PM

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

How can I use linters and static analysis tools to improve the quality and maintainability of my Go code?How can I use linters and static analysis tools to improve the quality and maintainability of my Go code?Mar 10, 2025 pm 05:38 PM

This article advocates for using linters and static analysis tools to enhance Go code quality. It details tool selection (e.g., golangci-lint, go vet), workflow integration (IDE, CI/CD), and effective interpretation of warnings/errors to improve cod

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version