Crafting Compile-Time Computations: Implementing a const fn in Rust
Rust's const fn allows functions to be evaluated at compile time, enabling performance optimizations and the creation of complex compile-time constants. This challenge will test your understanding of const fn by requiring you to implement a useful compile-time function. You will focus on creating a const fn that calculates a specific mathematical property.
Problem Description
Your task is to implement a const fn in Rust named fibonacci_const that calculates the nth Fibonacci number. The Fibonacci sequence is defined as follows:
- F(0) = 0
- F(1) = 1
- F(n) = F(n-1) + F(n-2) for n > 1
The fibonacci_const function should take a single u32 argument representing the index n in the Fibonacci sequence and return the corresponding Fibonacci number as a u32.
Key Requirements:
- The function must be a
const fn. - It should correctly calculate Fibonacci numbers for non-negative integers.
- It must handle the base cases F(0) and F(1).
Expected Behavior: The function should behave like a standard recursive or iterative Fibonacci implementation but be entirely evaluated at compile time.
Edge Cases:
n = 0should return0.n = 1should return1.- Consider potential overflow for larger
n, although for the given constraints,u32should suffice.
Examples
Example 1:
const FIB_5: u32 = fibonacci_const(5);
// FIB_5 should be 5
Explanation: F(0) = 0 F(1) = 1 F(2) = F(1) + F(0) = 1 + 0 = 1 F(3) = F(2) + F(1) = 1 + 1 = 2 F(4) = F(3) + F(2) = 2 + 1 = 3 F(5) = F(4) + F(3) = 3 + 2 = 5
Example 2:
const FIB_0: u32 = fibonacci_const(0);
// FIB_0 should be 0
Explanation:
The base case fibonacci_const(0) should return 0.
Example 3:
const FIB_10: u32 = fibonacci_const(10);
// FIB_10 should be 55
Explanation: Continuing the sequence: F(6) = 8 F(7) = 13 F(8) = 21 F(9) = 34 F(10) = 55
Constraints
- The input
nwill be au32such that0 <= n <= 30. (Note: F(30) is withinu32limits). - The output must be a
u32. - The function must be a
const fn.
Notes
- You can implement this using either recursion or iteration. However, be mindful that
const fnhas some limitations regarding heap allocation and certain complex control flow. - Consider how to handle the base cases efficiently within a
const fn. - The goal is to have the calculation guaranteed to happen at compile time, so you should be able to use the result in other
constcontexts.