A const fn is a Rust function permitted in a const context, where the compiler can interpret its call at compile time. The same function can also run normally after compilation. section 16.2
const NUMBER: u8 = give_eight();
const fn give_eight() -> u8 {
8
}
fn main() {
let mut my_vec = Vec::new();
my_vec.push(give_eight());
}
This example uses give_eight to initialize a constant at compile time and then calls it again while pushing a value into a Vec at runtime. section 16.2
Keep these practical rules in mind:
- Add const before fn when the function must be callable from a const context. section 16.2
- A const fn does not run only at compile time; ordinary calls remain allowed. section 16.2
- Const contexts restrict available operations, including allocations in the demonstrated case. section 16.2
- The permitted operations continue to expand as Rust stabilizes more const functionality. section 16.2
When a regular function is rejected
Changing const fn give_eight() to fn give_eight() makes const NUMBER: u8 = give_eight(); fail with an error explaining that constants can call only constant functions, tuple structs, and tuple variants. section 16.2
