Puzzle 23: Explanation
Let’s learn how to produce the Fibonacci series in Rust using constants.
We'll cover the following...
We'll cover the following...
Test it out
Press “Run” to see the output of the code.
Press + to interact
C++
const fn fib(n: u128) -> u128 {let mut a = 1;let mut b = 1;for _ in 2..n {let tmp = a + b;a = b;b = tmp;}b}fn main() {for i in 0..5 {println!("Fib {} = {}", i, fib(i));}}
Explanation
Marking a function as const
causes the function to run at compile time rather than at runtime. When a function runs at compile time, the compiler calculates the results beforehand from constant inputs, which can help speed up complex calculations that we might need later.
Suppose our program requires a lot of Fibonacci numbers. Without a const
function, our program would need to recalculate the numbers as needed, possibly more than once. However, by using a const
function, we can store these numbers as constant values in our program, dramatically improving its performance. ...