Here’s a Go program that defines and calls a Fibonacci function:
package main
import (
"fmt"
"strconv"
)
func main() {
// Prompt user for a positive integer
fmt.Println("Enter a positive integer:")
var input string
fmt.Scanln(&input)
// Parse input as integer
n, err := strconv.Atoi(input)
if err != nil {
fmt.Println("Invalid input. Please enter a positive integer.")
return
}
// Calculate the nth Fibonacci number
result := fibonacci(n)
// Print the result
fmt.Printf("The %dth Fibonacci number is %d\n", n, result)
}
func fibonacci(n int) int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fibonacci(n-1) + fibonacci(n-2)
}
}
Explanation:
fmt
for input/output, strconv
for string conversion.fmt.Scanln
.int
using strconv.Atoi
.err
check.fibonacci
function with the parsed number.Running the program:
main.go
.go run main.go
to execute the program.This program follows a similar structure to the Rust version, demonstrating a recursive approach to calculating Fibonacci numbers in Go.