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
We can omit the entire "const
fn
" syntax and just assign a const
value to the result of a block (in curly braces) that can be evaluated at compile-time.
main()
we access the pre-computed lookup table's entries.get_lookup_table()
and use verbose syntax, but the result is the same with the Rust compiler.const LOOKUP: [u8; 256] = { // Use a const function with more concise syntax to generate a lookup table. let mut result = [0; 256]; result[0] = 2; result[5] = 4; result[10] = 6; result }; fn main() { // Use lookup table. println!( "LOOKUP RESULTS: {}, {}, {}", LOOKUP[0], LOOKUP[1], LOOKUP[2] ); }LOOKUP RESULTS: 2, 0, 0
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.