See this code:
fn main() {
let something_const = 42;
fn multiply(nbr: i32) -> i32 {
nbr * something_const
}
println!("{}", multiply(1));
}
rustc
outputs that
error[E0434]: can't capture dynamic environment in a fn item; use the || { ... } closure form instead
--> main.rs:19:15
|
19 | nbr * something_const
| ^^^^^^^^^^^^^^^
But something_const
is not dynamic, because it is known at compile time.
Is it an equivalent in Rust of the C++ constexpr
mechanism?
constexpr
in C++ can be used in 2 different situations:Rust supports both, albeit in a limited fashion:
const
to declare a constant, instead oflet
, to declare that it is truly constantconst
to qualify a function, to declare that it can be evaluated at compile-timeIn your situation, you want the first usage:
Note that unlike with
let
, it is mandatory to annotate the constant with its type.Also, the compiler will complain about the naming; constants use
ALL_CAPS
.