CodeBlanks Logo Icon CodeBlanks

const fn

Write compile-time functions with const fn.

const fn

A const fn is a function that can be run at compile time. It can be used to compute the values of constants, statics and array lengths; in normal calls it works like an ordinary function:

const fn kare(x: u32) -> u32 {
    x * x
}

const BOYUT: u32 = kare(4);           // at compile time: 16
static TABLO: [u8; BOYUT as usize] = [0; BOYUT as usize];
let n = kare(5);                      // works at runtime too

A computation done at compile time adds nothing to the program's running time.

Compile-time tables

Loops and conditions can be used inside a const fn. This makes it possible to generate lookup tables at compile time:

const fn kareler<const N: usize>() -> [u32; N] {
    let mut t = [0; N];
    let mut i = 0;
    while i < N {
        t[i] = (i * i) as u32;
        i += 1;
    }
    t
}

const TABLO: [u32; 5] = kareler::<5>();   // [0, 1, 4, 9, 16]

A for loop can't be used in const context yet, because it uses the iterator trait; while is used.

Practice Compile-time size

Write const fn kare(x: u32) -> u32 and define const BOYUT: u32 = kare(4);. Create the array [0u8; BOYUT as usize]; print BOYUT and the array's length separated by a space.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
const fn kare(x: u32) -> u32 {
    x * x
}

const BOYUT: u32 = kare(4);

fn main() {
    let dizi = [0u8; BOYUT as usize];
    println!("{} {}", BOYUT, dizi.len());
}

Expected output

16 16

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which can't be used inside a const fn?

  • Arithmetic
  • Heap allocation (Vec::push, Box::new) and I/O Correct answer
  • if and match
  • while loops

Explanation: At compile time only deterministic, side-effect-free work can be done; what's allowed grows with each release.

2 Compile-time function

Question
____ fn kare(x: u32) -> u32 {
    x * x
}
const BOYUT: u32 = kare(4);
Answer
const fn kare(x: u32) -> u32 {
    x * x
}
const BOYUT: u32 = kare(4);

Explanation: To compute a constant value, the function must be a const fn.

3 Expression and evaluation time

Term Meaning
const B: u32 = kare(4); Compile time
let n = kare(5); Runtime (usually)
[0u8; kare(2) as usize] Compile time (array length)
kareler::<5>() [0, 1, 4, 9, 16]

All lessons in Advanced