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

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

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

将指针传递给 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

怪兽AI数字人
怪兽AI数字人

数字人短视频创作,数字人直播,实时驱动数字人

怪兽AI数字人 44
查看详情 怪兽AI数字人

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

示例 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中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号