Search⌘ K
AI Features

Solution Review 3: Find nth Fibonacci Number

Explore how to write a recursive function in Rust to calculate the nth Fibonacci number. Understand the base case and recursive calls that define this function, and see how recursion works in Rust through step-by-step explanations and examples. This lesson builds on your knowledge of Rust functions and prepares you for working with more complex data types.

We'll cover the following...

Solution:

Rust 1.40.0
fn fibonacci(term: i32) -> i32 {
match term {
0 => 0,
1 => 1,
_ => fibonacci(term-1) + fibonacci(term-2),
}
}
fn main(){
println!("fibonacci(4)={}",fibonacci(4));
}

Explanation

A recursive function, fibonacci, takes a parameter term of type i32 and returns an integer of type i32, i.e., the nth term of the Fibonacci number.

The recursive function ...