duanliang1898 2017-04-18 17:39
浏览 53
已采纳

为什么defer在周围函数中定义的变量的行为与命名结果不同?

The program below returns

<nil>
hello

I expected both to return "hello" but it's not the case. I've found that the behaviour is given as example in the language spec.

For instance, 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.

My question is: why does defer works differently with variables defined in the surrounding function than with named results? Isn't it just a closure executed before the surrounding function returns?

package main

import (
    "errors"
    "fmt"
)

func main() {

    fmt.Println(up())
    fmt.Println(up2())

}

func up() error {
    var err error
    defer func() {
        err = errors.New("hello")
    }()
    return err
}

func up2() (err error) {
    defer func() {
        err = errors.New("hello")
    }()
    return err
}

func up3() error {
    var err error
    fn := func() {
        err = errors.New("hello")
    }
    fn()
    return err
}
  • 写回答

1条回答 默认 最新

  • doulangpeng3933 2017-04-18 18:46
    关注

    The spec says:

    A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

    A key point is that the deferred function is executed after the return statement is executed.

    The spec also says:

    A "return" statement in a function F terminates the execution of F, and optionally provides one or more result values. Any functions deferred by F are executed before F returns to its caller.

    The function up returns nil because the deferred function sets err after the return statement provides the function result.

    The function up2 overwrites the result value set by the return statement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 扫描枪扫条形码出现问题
  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?