为什么defer在周围函数中定义的变量的行为与命名结果不同? [英] Why defer behaves differently with variables defined in the surrounding function than named results?

查看:40
本文介绍了为什么defer在周围函数中定义的变量的行为与命名结果不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的程序返回

<nil>
hello

我希望两个都返回"hello",但事实并非如此.我发现该行为是使用 spec 规范给出的示例.

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.

我的问题是:为什么defer在周围函数中定义的变量与命名结果不同?

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
}

推荐答案

规范说:

"defer"语句调用一个函数,该函数的执行被推迟到周围函数返回的那一刻,这是因为周围函数执行了return语句,到达了函数体的末尾,或者是因为相应的goroutine感到恐慌./p>

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.

关键是要在执行return语句后执行延迟函数.

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

规范也说:

函数F中的返回"语句终止F的执行,并可选地提供一个或多个结果值.F延迟的任何函数都将在F返回其调用方之前执行.

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.

函数 up 返回nil,因为延迟的函数在return语句提供函数结果后设置了 err .

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

函数 up2 覆盖return语句设置的结果值.

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

这篇关于为什么defer在周围函数中定义的变量的行为与命名结果不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆