golang 中的延迟、返回和参数评估

package main


import "fmt"


// fibonacci is a function that returns

// a function that returns an int.

func fibonacci() func() int {

    a, b := 0, 1

    return func() int {

        defer func() {a, b = b, a + b}()

        return a

    }

}


func main() {

    f := fibonacci()

    for i := 0; i < 10; i++ {

        fmt.Println(f())

    }

}


有人可以解释为什么输出从 0, 1, 1, 2, 3, 5 .... 而不是 1, 1, 2, 3, 5, ..... 开始吗?


据我了解, defer 会在 return 语句之前执行,这意味着 a、b 已经更新为 1、1 并且应该返回 1?也许它与表达式被评估或绑定的时间有关,也许返回已经将 a 绑定为 0 然后在返回之前检查是否存在 defer 语句?


go 中的任何内部代码参考都会非常有帮助。


编辑 1:这是我在了解延迟后尝试的练习https://go.dev/tour/moretypes/26 。


慕侠2389804
浏览 75回答 2
2回答

繁华开满天机

在更改局部变量的值为时已晚defer之后执行。return aa您可能将它与defer更改命名的返回值混淆了。这是不同的情况,因为即使在 之后更改它return,该函数实际上也会返回它。

素胚勾勒不出你

有人可以解释为什么输出从 0, 1, 1, 2, 3, 5 .... 而不是 1, 1, 2, 3, 5, ..... 开始吗?如果周围函数通过显式 return 语句返回,则延迟函数在该 return 语句设置任何结果参数之后但在函数返回其调用者 Defer_statements之前执行因为 defer 函数执行并将 a 的值从 0 更改为 1 但 a 的值已经是返回显式。func fibonacci() func() int {&nbsp; &nbsp; a, b := 0, 1&nbsp; &nbsp; return func() int {&nbsp; &nbsp; &nbsp; &nbsp; defer func() {a, b = b, a + b}()&nbsp; &nbsp; &nbsp; &nbsp; return a&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP