【问题标题】:Go closure with naked return以赤裸裸的回报关闭
【发布时间】:2018-03-11 22:18:47
【问题描述】:

我正在玩 Go 并试图实现一个 fibonacci 函数,该函数返回一个返回斐波那契数的闭包。问题可以在 go tool tour 中找到。这是一个使用常规(非裸)返回的闭包实现:

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    a := 0
    b := 1
    return func() int {
        t := a + b
        a = b
        b = t
        return b
    }
}

func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}

该函数正确返回以下内容:

1
2
3
5
8
13
21
34
55
89

我尝试通过尝试在闭包函数中使用裸返回来以不同的方式编写 fibonacci 函数,但它会产生错误:

./compile20.go:9:7: b 已声明但未使用

这是产生错误的代码

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    a := 0
    b := 1
    return func() (b int) {
        t := a + b
        a = b
        b = t
        return
    }
}

func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}

有人知道变量b 没有被使用吗? b显然用在闭包函数的第一行(t := a + b)。

【问题讨论】:

  • 参数b int 遮蔽了局部变量b := 1,这就是为什么在func fibonacci()中从未使用b的原因@
  • 提示:你可以使用多重赋值来简化你的代码:a, b = b, a+b

标签: go closures


【解决方案1】:

在返回段中定义的变量会在外部作用域中隐藏同名变量。在您返回的函数中,b 指的是返回值中定义的那个。

您可以删除b的第一个声明(和初始化)并且程序通过检查,尽管逻辑不正确。

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    a := 0
    b := 1 // declare a variable b and initialize with 1
    return func() (b int) { // declare a variable b with default initialization
        t := a + b // b refers to the variable defined in the return value
        a = b
        b = t
        return
    }
}

【讨论】:

  • 我明白了。不知道命名返回参数不能在函数外定义
猜你喜欢
  • 1970-01-01
  • 2012-11-08
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
  • 2012-12-03
  • 2021-09-16
  • 2021-12-04
  • 1970-01-01
相关资源
最近更新 更多