Rust array
Created By: chatGPT
Arrays in Rust are fixed-size collections of elements of the same type. They are useful for storing multiple values that can be accessed by an index. In Rust, the size of an array must be known at compile time.
let numbers: [i32; 5] = [1, 2, 3, 4, 5];
You can also initialize an array with the same value for all its elements. This can be done using the following syntax:
let repeated: [i32; 4] = [0; 4]; // Array of four 0s
Accessing elements in an array can be done using indexing. Keep in mind that Rust uses zero-based indexing.
let first_number = numbers[0]; // Access the first element
You can also use the length of an array to iterate over its elements. The length can be retrieved using the
.len()
method.let length = numbers.len();
To iterate through an array, you can use a for loop. Here is an example of how to print all elements in an array:
for number in &numbers {\n println!("{}", number);\n}
It's important to note that arrays are stored on the stack. For larger collections, consider using a vector which allows dynamic resizing.
let mut numbers_vector: Vec<i32> = vec![1, 2, 3];\nnumbers_vector.push(4);