duanliang1898 2017-04-18 17:39
浏览 53


The program below returns


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 (

func main() {



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")
    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 matlab+波形匹配算法
    • ¥15 转录组分析做聚类树图时癌旁组被分到了癌组
    • ¥15 大一Python字典
    • ¥15 multisim电路设计(相关搜索:设计报告)
    • ¥15 从github上下载的项目到ecplise上咋运行
    • ¥15 PC-lint Plus
    • ¥15 gpl24676注释
    • ¥15 php5.3内存泄露
    • ¥15 DigSilent如何复制复合模型到自己案例?
    • ¥15 求日版华为b610s-77a 官方公版固件,有偿