The following function computes a the last element in a Fibonacci sequence in Go language.
package main
import (
"fmt"
)
type Element struct {
Next *Element
Value interface{}
}
type Stack struct {
Top *Element
Count int
}
func (stack *Stack) Push(value interface{}) {
el := Element{
Value: value,
Next: stack.Top,
}
stack.Top = &el
stack.Count++
}
func (stack *Stack) Peek() (value interface{}) {
if stack.Top != nil {
value = stack.Top.Value
}
return
}
func (stack *Stack) Pop() (value interface{}) {
if stack.Top != nil {
value = stack.Top.Value
stack.Top = stack.Top.Next
stack.Count--
}
return
}
func (stack *Stack) Size() int {
return stack.Count
}
func Fibonacci(n int) int {
if n == 0 {
return 0
}
if n == 1 {
return 1
}
//for n >= 2 the initial stack has the 0 and 1 values
stack := Stack{}
stack.Push(0)
stack.Push(1)
// loop from n to 2
for n > 1 {
//pop two top elements from stack
term1 := stack.Pop().(int)
term2 := stack.Pop().(int)
//push back the first popped element, this will become term2 on the next iteration
stack.Push(term1)
//push the sum of the two elements, this will be the Top element on the next iteration
stack.Push(term1 + term2)
//move to the next iteration
n--
}
//the top element in stack represents the last element in the Fibonacci sequence for a given n position
return stack.Pop().(int)
}
func FibonacciTest() {
fmt.Println("F0 -> 0", 0 == Fibonacci(0))
fmt.Println("F1 -> 1", 1 == Fibonacci(1))
fmt.Println("F2 -> 1", 1 == Fibonacci(2))
fmt.Println("F3 -> 2", 2 == Fibonacci(3))
fmt.Println("F4 -> 3", 3 == Fibonacci(4))
fmt.Println("F5 -> 5", 5 == Fibonacci(5))
fmt.Println("F6 -> 8", 8 == Fibonacci(6))
fmt.Println("F7 -> 13", 13 == Fibonacci(7))
fmt.Println("F8 -> 21", 21 == Fibonacci(8))
fmt.Println("F9 -> 34", 34 == Fibonacci(9))
fmt.Println("F20 -> 6765", 6765== Fibonacci(20))
}
func main() {
FibonacciTest()
}
I'm new to Go language. I'm interested if this code can be improved or what I can add to be more like a Go style. I'm not very sure about the .(int)
"conversion" and any explanation will be appreciated.