Sometimes we want the compiler to pre-compute values at compile time. If you have ever done programming in C++, you would have heard constexpr
A few days ago, I was exploring Rust’s Unstable Book and found pretty much same feature in Rust, which is const_fn. I started exploring this feature more after the recent Rust release 1.33.0, in which Rust team has announced major improvements const fn
const fn
const fn
is a pure function, which means the return value does not depend on anything but the function parameters. For same input, it will always return same output. Let’s see a small example:-
const fn square_area(a: i32) -> i32 {
let area = a * a;
area
}
const AREA: i32 = square_area(5);
The 5
square_area(5)
Before release 1.33.0, you were not allowed to let
Compiling variables v0.1.0 (/home/ayush/workspace/variables)
error: local variables in const fn are unstable
--> src/main.rs:20:9
|
20 | let area = a * a;
| ^^^^
error: aborting due to previous error
error: Could not compile `variables`.
In square_area
const
const
context, the function is interpreted by the compiler at compile time. const fn
will be guaranteed to evaluate at compile time when the result is stored into a constant. If we call it outside constant context, there will be no difference between const fn
and a normal fn
.
A const function cannot call a non-const function. But const fn
that can’t be evaluated at compile-time. For example- you cannot write
const fn x(a: i32) -> i32 {
add(a)
}
fn add(x: i32) -> i32 {
x + 1
}
Here you will get a compilation error. const fn
if
match
&&
||
