Home
Rust
const fn Example
Updated Nov 13, 2024
Dot Net Perls
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.
Lookup Table
const Generic
include_bytes
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 13, 2024 (edit link).
Home
Changes
© 2007-2025 Sam Allen