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.
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.
const
function is not always run at compile-time—it must be called in a const
context, like when used in a const
statement.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
If we generate a 10000-element array with a const
function, the binary size of the program will increase by the memory size needed.
byte
lookup table in the executable itself.Size
issueBy 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.
Const functions can be called to assign program constants. Some features like for
-loops cannot be used—instead, we can use while
-loops.