liveBook · Manning

Const fn

As explained in Learn Rust in a Month of Lunches

A const fn is a Rust function eligible for evaluation at compile time when called in a compile-time context.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines compile-time eligibility, demonstrates restrictions, and notes evolving capabilities without detailing compiler internals.
Examples
Uses give_eight, a Vec push, a non-const compiler error, and Mutex::new with Vec::new for static initialization.
What it assumes
Assumes ordinary Rust functions, constants, and compile-time contexts, while explaining const fn from its relationship to fn.
What you can do after
Apply it by marking eligible functions const and testing compiler feedback when using them in compile-time contexts.
How it connects
Connects const fn with const contexts, constants, allocations, static initialization, and standard-library const functions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.