Home > Net >  The way for slice to expend itself in go
The way for slice to expend itself in go

Time:12-03

I am new to go and now evaluate a demo function about slice with Fibonacci sequence

package main

import "fmt"

func fbn(n int) []uint64 {
    fbnSlice := make([]uint64, n)
    fbnSlice[0] = 1
    fbnSlice[1] = 1

    for i := 2; i < n; i   {
        fbnSlice[i] = fbnSlice[i-1]   fbnSlice[i-2]
    }
    return fbnSlice

}

func main() {
    fnbSlice := fbn(5)
    fmt.Println(fnbSlice)
}

It will print "[1 1 2 3 5]" My doubt is how the slice add it's len to 5, thanks!

CodePudding user response:

make([]uint64, n)

Will make a slice of length n, filled with zeros. Hence, fbn(5) will produce a slice of length 5.

CodePudding user response:

In the code, the function fbn is defined with an input parameter n which determines the length of the slice. The slice is created with a length of n using the make function and the first two elements of the slice are initialized to 1. Then, in the for loop, the subsequent elements are calculated by summing the previous two elements in the slice. Finally, the completed slice is returned.

In the main function, the fbn function is called with an input of 5, so the resulting slice will have a length of 5. This is why the output is [1 1 2 3 5] - it is the first 5 elements of the Fibonacci sequence.

  • Related