find the nth fibonacci number in rust

To find the nth Fibonacci number in Rust, you can use a recursive function. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers. The sequence starts with 0 and 1, which are the first two Fibonacci numbers.

Here's one way to implement the function:

main.rs
fn fibonacci(n: u32) -> u32 {
    match n {
        0 => 0,
        1 => 1,
        _ => fibonacci(n-1) + fibonacci(n-2),
    }
}
130 chars
8 lines

This function takes an unsigned 32-bit integer n as input and returns the nth Fibonacci number as an unsigned 32-bit integer. The function uses pattern matching to handle the base cases where n is 0 or 1, and then recursively calls itself with n-1 and n-2 to find the nth Fibonacci number.

To test the function, you can call it with a specific value of n and print the result:

main.rs
fn main() {
    let n = 10;
    let result = fibonacci(n);
    println!("The {}th Fibonacci number is {}", n, result);
}
121 chars
6 lines

This will output:

main.rs
The 10th Fibonacci number is 55
32 chars
2 lines

gistlibby LogSnag