dqwr32867 2017-09-30 00:46
浏览 32
已采纳

赤裸裸地退场

I am playing around with Go and am trying to implement a fibonacci function that returns a closure that returns fibonacci numbers. The problem can be found in the go tool tour. Here is a closure implementation that uses a regular (non-naked) return:

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())
    }
}

The function correctly returns the following:

1
2
3
5
8
13
21
34
55
89

I tried writing the fibonacci function differently by trying to use a naked return within the closure function, but it produces an error:

./compile20.go:9:7: b declared and not used

Here is the code that generates the error

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())
    }
}

Anybody know how the variable b is not being used? b is obviously used in the first line of the closure function (t := a + b).

  • 写回答

1条回答 默认 最新

  • dongzhan1492 2017-09-30 01:22
    关注

    Variables defined in the return segment shadow the variable with the same name in the outer scope. Inside your returned function, b refers to the one defined in the return value.

    You can remove the first declaration (and initialization) of b and the program passes the check, although the logic is not right.

    // 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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置