开发者

Returning the lenght of a vector idiomatically

I'm writing a function that r开发者_Go百科eturns a sequence of numbers of variable length:

func fib(n int) ??? {
    retval := ???
    a, b := 0, 1
    for ; n > 0; n-- {
        ??? // append a onto retval here
        c := a + b
        a = b
        b = c
    }
}

It can be observed that the final length of the returned sequence will be n. How and what should fib return to achieve idiomatic Go? If the length was not known in advance, how would the return value, and usage differ? How do I insert values into retval?


Here, we know how many numbers; we want n Fibonacci numbers.

package main

import "fmt"

func fib(n int) (f []int) {
    if n < 0 {
        n = 0
    }
    f = make([]int, n)
    a, b := 0, 1
    for i := 0; i < len(f); i++ {
        f[i] = a
        a, b = b, a+b
    }
    return
}

func main() {
    f := fib(7)
    fmt.Println(len(f), f)
}

Output: 7 [0 1 1 2 3 5 8]


Here, we don't know how many numbers; we want all the Fibonacci numbers less than or equal to n.

package main

import "fmt"

func fibMax(n int) (f []int) {
    a, b := 0, 1
    for a <= n {
        f = append(f, a)
        a, b = b, a+b
    }
    return
}

func main() {
    f := fibMax(42)
    fmt.Println(len(f), f)
}

Output: 10 [0 1 1 2 3 5 8 13 21 34]


You could also use IntVector from the Go vector package. Note that type IntVector []int.


Don't use Vectors, use slices. Here are some mapping of various vector operations to idiomatic slice operations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜