Is this a preference against functional programming or just you can't see the use case? One of the reasons that I like Rust comparing to functional languages is that it can support both.
I think I'm pragmatic enough. If imperative is easier, then I'll go with the loop. However, it means that you probably only need the Fibonacci series for one particular time in all of your program. If that's the case, then certainly go with the loop.
There is a reasoning behind the iterator/functional model and it enable you to do stuff that would be hard/impossible with the loop.
First, you start by defining a general fibonnaci sequence function
fn fib_seq() -> std::iter::RepeatWith<impl FnMut() -> u32> {
std::iter::repeat_with({
let mut state = (1, 1);
move || {
state = (state.1, state.0 + state.1);
state.0
}
})
}
This function returns an Iterator. Iterators in Rust are both lazy and zero-cost. So they won't execute unless they need to and also they are as good as the loop.
This iterator pattern allows you to use your code in different ways. Let's say you want to take the first 99 fib numbers and calculate their sum
let sum: u32 = fib_seq().take_while(|&x| x < 100).sum();
Let's say you want to take the first 99 numbers that are even and take calculate their sum
let sum_filter: u32 = fib_seq()
.take_while(|&x| x < 100)
.filter(|x| x % 2 == 0)
.sum();
This is not possible to do with imperative code without code repetition and making your code more complex.
I hope you can start to see how functional code can be useful ![]()