26 January 2023
Variable bindings with let
are immutable by default. But Rust also has a separate
concept of constants that are introduced with the keyword const
:
const MIN_IN_SECONDS: u32 = 60;
By convention constants should have names in all-uppercase. A constant definition always has a type and is initialized by a constant expression. You can read up on the details in Constant evaluation in the Rust Reference, but basically literals and operations on them are allowed, for example:
const HOUR_IN_SECONDS: u32 = 60 * 60;
Also allowed are calls to const functions, which are declared with const fn
. Here’s a
silly example:
const HALF_HOUR_IN_SECONDS: u32 = half(HOUR_IN_SECONDS);
const fn half(x: u32) -> u32 {
x / 2
}