Go — declared and not used error, when I think I have done so to the variable

前端 未结 2 728
梦如初夏
梦如初夏 2021-01-12 11:11

What\'s wrong with this code?

package main

import \"fmt\"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func(         


        
2条回答
  •  盖世英雄少女心
    2021-01-12 11:51

    If you make the changes suggested by Kevin Ballard, then,

    package main
    
    import "fmt"
    
    // fibonacci is a function that returns
    // a function that returns an int.
    func fibonacci() func() int {
        prev := 0
        curr := 1
        return func() int {
            temp := curr
            curr = curr + prev
            prev = temp
            return curr
        }
    }
    
    func main() {
        f := fibonacci()
        for i := 0; i < 10; i++ {
            fmt.Println(f())
        }
    }
    

    Output:

    1
    2
    3
    5
    8
    13
    21
    34
    55
    89
    

    The output is not the Fibonacci sequence.

    For the Fibonacci sequence,

    package main
    
    import "fmt"
    
    func fibonacci() func() int {
        a, b := 0, 1
        return func() (f int) {
            f, a, b = a, b, a+b
            return
        }
    }
    
    func main() {
        f := fibonacci()
        for i := 0; i < 10; i++ {
            fmt.Println(f())
        }
    }
    

    Output:

    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    

提交回复
热议问题