In Rust, defining a const array in the global scope can be achieved by using the const keyword at the module level. Such arrays are determined at compile-time and remain unchanged throughout the program's runtime.
Here is a simple example demonstrating how to define a global const array in Rust:
rust// Define a global constant array const MY_ARRAY: [i32; 3] = [1, 2, 3]; fn main() { // Use the global constant array in the main function println!("The first element of the array is: {}", MY_ARRAY[0]); println!("The second element of the array is: {}", MY_ARRAY[1]); println!("The third element of the array is: {}", MY_ARRAY[2]); }
In this example:
MY_ARRAYis a global constant array containing three integers.- Within the
mainfunction, we access and print each element of the array.
Arrays defined with const must be determinable at compile-time, so they typically require initialization with constant expressions. This means each element and the length of the array must be constants.
Furthermore, since const in Rust denotes true constants (immutable), this approach is well-suited for defining data that does not need to be modified during program execution. For instance, program configuration, predefined datasets, or any other fixed data.