Arrays are collections of same-type-data values stored in contiguous memory locations. In Rust, arrays are created using square brackets []
and their size needs to be known at compile time. An array whose size is not defined is called a slice.
There are three ways for an immutable array to be created in Rust:
The following program creates an array of five elements without defining their data types. Note that the len()
function is a built-in function that returns the length of the array.
fn main() {let arr = [1,2,3,4,5];println!("The array is {:?}", arr);println!("The length of the array is: {}", arr.len());}
The following program creates an array with an explicitly defined data type and size:
fn main() {let arr:[i32;5] = [1,2,3,4,5];println!("The array is {:?}", arr);println!("Length of the array is: {}", arr.len());}
Note:
arr:[i32;5]
(syntax:i32
) means that the array consists of 32-bit integers and has a length of5
.
An array can also be created and initialized when all of its elements have a single default value:
fn main() {let arr:[i32;3] = [0;3]; // The size of the array needs to be specified again during initialization.println!("The array is: {:?}", arr);println!("Length of the array is: {}", arr.len());}
All the arrays shown above are immutable: their contents cannot be changed. To create a mutable array in Rust, use the mut
keyword. The following code snippet creates a mutable array and changes the value of some of its elements:
fn main() {let mut arr:[i32;5] = [1,2,3,4,5];println!("Original array: {:?}",arr);arr[1] = 0;arr[2] = 100;arr[4] = -50;println!("Changed array: {:?}",arr);}
Free Resources