Rust - Arrays
In Rust, arrays are a fixed-size collection of elements of the same type. Here’s a detailed overview of arrays in Rust:
Creating Arrays
Arrays in Rust are created using square brackets []
and specifying the type and size. All elements
in an array must be of the same type, and the size of the array must be known at compile time.
Basic Array Declaration
rustfn main() {
let arr: [i32; 5] = [1, 2, 3, 4, 5];
println!("{:?}", arr); // Output: [1, 2, 3, 4, 5]
}
[i32; 5]
specifies an array of 5i32
elements.- The
{:?}
format specifier is used withprintln!
to print arrays in debug format.
Array with Repeated Values
You can also initialize an array with repeated values using the following syntax:
rustfn main() {
let arr: [i32; 5] = [3; 5];
println!("{:?}", arr); // Output: [3, 3, 3, 3, 3]
}
Here, [3; 5]
creates an array of 5 elements, all initialized to 3
.
Accessing and Modifying Elements
You can access and modify array elements using indexing. Array indices start at 0.
Accessing Elements
rustfn main() {
let arr = [10, 20, 30, 40, 50];
let element = arr[2]; // Access the third element
println!("{}", element); // Output: 30
}
Modifying Elements
rustfn main() {
let mut arr = [10, 20, 30, 40, 50];
arr[2] = 35; // Modify the third element
println!("{:?}", arr); // Output: [10, 20, 35, 40, 50]
}
Arrays must be mutable if you want to modify their elements, so you need to declare the array with
mut
.
Array Length
You can obtain the length of an array using the len()
method.
rustfn main() {
let arr = [1, 2, 3, 4, 5];
let length = arr.len();
println!("Length of the array: {}", length); // Output: Length of the array: 5
}
Slicing Arrays
You can create slices of arrays to view a subset of elements.
Creating a Slice
rustfn main() {
let arr = [1, 2, 3, 4, 5];
let slice = &arr[1..4]; // Slice from index 1 to 3 (not including 4)
println!("{:?}", slice); // Output: [2, 3, 4]
}
Multidimensional Arrays
Rust supports multidimensional arrays by nesting arrays.
Two-Dimensional Array
rustfn main() {
let matrix: [[i32; 3]; 2] = [
[1, 2, 3],
[4, 5, 6],
];
println!("{:?}", matrix); // Output: [[1, 2, 3], [4, 5, 6]]
}
Iterating Over Arrays
You can iterate over arrays using a for
loop.
Iterating Over Elements
rustfn main() {
let arr = [10, 20, 30, 40, 50];
for element in arr.iter() {
println!("{}", element);
}
}
Iterating with Indexes
rustfn main() {
let arr = [10, 20, 30, 40, 50];
for (index, &element) in arr.iter().enumerate() {
println!("Index: {}, Element: {}", index, element);
}
}
Summary
- Array Declaration:
[type; size]
- Accessing Elements:
array[index]
- Modifying Elements:
array[index] = value
- Array Length:
array.len()
- Slicing:
&array[start..end]
- Multidimensional Arrays: Nested arrays
- Iteration: Using
for
loops with.iter()
and.enumerate()
Arrays in Rust are a fundamental data structure with fixed size and type, making them efficient and straightforward to use for various purposes.