Go面试:命名返回值是defer延迟函数在surrounding函数返回前修改返回值的唯一途径

package main

func main() {
        println(func1())
        println(func2())
        println(func3())
}

func func1() (t int) {
        defer func() {
                t = 3
        }()
        return t
}
func func2() int {
        t := 0
        defer func() {
                t = 3
        }()
        return t
}
func func3() (t int) {
        defer func() {
                t = 3
        }()
        return 2
}

输出:
3
0
3
可见defer可以在函数返回前修改命名返回值,非命名返回值则不能修改。换句话说,命名返回值是defer修改函数返回值的唯一途径。

“If the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned”

另外需要注意的是:在有命名返回值的函数func3里return 2 等价于t = 2 然后 return。例如下列返回值是1

func b() (i int) {  // return 1 
    i = 2
    return 1
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值