Const fn. Often Rust programs have some lookup tables or other data that needs to be used. This data does not need to be generated each time the program runs.
With const functions, we can generate lookup tables at compile-time. This may increase the executable size, but can speed up program startup.
Example. To begin, we note that a const function is like any other function in Rust, but it has some limitations. The for-loop is not supported, so we must use while.
Important A const function is not always run at compile-time—it must be called in a const context, like when used in a const statement.
Detail We can pass arguments to a const function, and return a value like an array from one. Even loops can be used.
const LOOKUP: [u8; 10000] = get_lookup_table(&[1, 2, 3]);
const fn get_lookup_table(args: &[u8]) -> [u8; 10000] {
// Generate a lookup table array at compile-time with a const function.
let mut result = [0; 10000];
result[0] = args[0] * 10;
result[1] = args[1] * 10;
// Set the rest of the values with a while-loop.
let mut i = 2;
while i < result.len() {
result[i] = i as u8;
i += 1;
}
result
}
fn main() {
// Use lookup table.
println!("Result: {}", LOOKUP[1]);
}Result: 20
Considerations. If we generate a 10000-element array with a const function, the binary size of the program will increase by the memory size needed.
Info In the example program, we can find the 10,000-byte lookup table in the executable itself.
Size issue. By using a const array in this way, we increase the size of the program. The benefits would be greater for smaller lookup tables, as this would cause less size increase.
A summary. Const functions can be called to assign program constants. Some features like for-loops cannot be used—instead, we can use while-loops.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 10, 2022 (edit link).