fibonacci sequence in go

Here is an implementation of fibonacci sequence in Go using both loops and recursion:

Using loops:

main.go
func fibonacciLoop(n int) []int {
    fib := make([]int, n)
    fib[0], fib[1] = 0, 1
    for i := 2; i < n; i++ {
        fib[i] = fib[i-1] + fib[i-2]
    }
    return fib
}
175 chars
9 lines

Using recursion:

main.go
func fibonacciRecursive(n int) int {
    if n <= 1 {
        return n
    }
    return fibonacciRecursive(n-1) + fibonacciRecursive(n-2)
}
139 chars
7 lines

You can call the functions like this:

main.go
fibLoop := fibonacciLoop(10)
fmt.Println(fibLoop) // Output: [0 1 1 2 3 5 8 13 21 34]

fibRec := fibonacciRecursive(10)
fmt.Println(fibRec) // Output: 55
154 chars
6 lines

gistlibby LogSnag