Define a function with the `const fn` keyword to allow the compiler to evaluate it at compile time for constant expressions.
Use the const keyword before fn to define a function that the compiler can evaluate at compile time.
const fn square(x: i32) -> i32 {
x * x
}
const ANSWER: i32 = square(6);
This requires the function body to contain only operations allowed in constant contexts, such as basic arithmetic and recursion, excluding dynamic allocations or trait calls.
A const fn is a function that runs while your code is being compiled, not when it runs. This lets you calculate values like math formulas or configuration constants ahead of time, making your program faster and smaller. Think of it as doing your homework before the test starts so you don't have to waste time during the exam.