首页 > 后端开发 > Golang > 正文

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

WBOY
发布: 2024-02-13 12:24:09
转载
638 人浏览过

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

在 PHP 编程中,指针传递给 go defer 函数时可能出现不起作用的情况。PHP 中的指针用于存储变量的内存地址,通过传递指针,可以在函数内部修改原始变量的值。然而,当将指针传递给 go defer 函数时,有时会出现无法修改原始变量的情况。这可能是由于 go defer 函数在执行时会创建一个新的 Goroutine,而指针可能指向了不同的内存空间,导致无法正确修改变量的值。因此,在 PHP 编程中,应谨慎使用指针传递给 go defer 函数,以避免出现意想不到的问题。

问题内容

在我的代码中,我尝试使用 numaddr 来记录 defer 语句后 num 的变化

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

func main() {
    deferrun()
}

登录后复制

但我得到 num 是 1 而不是 2,为什么 defer 函数使用 *numaddr 的值而不是地址?

那我试试另一种方法

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()
}
登录后复制

这次它起作用了,我得到 num 是 2,所以我想也许 defer fmt.printf(something) 在声明它时立即存储了字符串,并且当 defer 函数实际运行时没有使用 numaddr ?

解决方法

有趣的问题。要回答这个问题,你必须知道一个规则,就像这个 go 教程 https://go.dev/游览/流量控制/12

延迟调用的参数会立即计算,但直到周围函数返回时才会执行函数调用。

示例 1:告诉 defer 函数打印位于指定内存地址的值。

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  
}
登录后复制

输出将为 2。

示例 2:告诉 defer 函数打印指定的值。

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  
}
登录后复制

输出将为 1。

以上是将指针传递给 go defer 函数不起作用的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!