Fibonblerfi

2025-10-30

I’m learning Rust and as my first little thing I’ve written a small script that takes an input N and generates the corresponding Fibonacci number. The input is limited to a u8 that is 100 or less, and the output type is u128 because F100 is a really big number. I would like to follow up with a version where I implement my own input type with my own parse implementation that does the bounds check.

The actual Fibonacci implementation feels a bit clunky, if only because I’m so used to reaching for tail recursion and I don’t think I have that in Rust (there is maybe a crate, but a lot of what I was reading was a few years old and the current state was unclear and I got overwhelmed).

If anyone is so moved: I am very much a beginner on my Rust journey, and any tips towards idiomatic Rust would be welcome.

 1use std::io;
 2
 3fn main() {
 4    println!("Enter fibonacci number to generate.");
 5    let n: u8 = loop {
 6        let mut string_n = String::new();
 7        io::stdin()
 8            .read_line(&mut string_n)
 9            .expect("Failed to read number!");
10
11        match string_n.trim().parse() {
12            Ok(num) => {
13                if num > 100 {
14                    println!("Please enter a positive integer less than 101.");
15                    continue;
16                } else {
17                    break num;
18                }
19            }
20            Err(_) => {
21                println!("Please enter a positive integer.");
22                continue;
23            }
24        };
25    };
26
27    let generated = match n {
28        0 => 0,
29        1 => 1,
30        _ => fibonacci(n),
31    };
32
33    println!("The {n}th fibonacci number is {generated}!")
34}
35
36fn fibonacci(n: u8) -> u128 {
37    let mut minus2: u128 = 0;
38    let mut minus1: u128 = 1;
39    let mut maybe_nth: u128 = 1;
40    let mut counter = n;
41    while counter > 1 {
42        maybe_nth = minus2 + minus1;
43        minus2 = minus1;
44        minus1 = maybe_nth;
45        counter -= 1;
46        println!("debug counter: {counter}, maybe_nth: {maybe_nth}")
47    }
48    maybe_nth
49}