In Rust, dynamic arrays are typically implemented using the Vec<T> type, where T represents the type of elements in the array. Vec<T> is a growable array that can dynamically adjust its capacity.
The following are the basic steps to create and manage dynamic arrays:
-
Create a new dynamic array:
rustlet mut vec = Vec::new(); // Initialize an empty dynamic arrayOr, if you know the elements in the array:
rustlet vec = vec![1, 2, 3, 4, 5]; // Create and initialize the array using a macro -
Add elements to the dynamic array:
rustvec.push(6); // Append an element to the end of the array -
Read elements from the dynamic array: Access elements by index, ensuring the index is within bounds to avoid causing a panic:
rustif let Some(value) = vec.get(0) { // Safely access the element at index 0 println!("The first element is {}", value); } else { println!("No element at index 0"); } -
Remove elements from the dynamic array:
rustlet last_element = vec.pop(); // Remove and return the last element of the array if let Some(value) = last_element { println!("Popped element: {}", value); } -
Iterate over elements in the dynamic array:
rustfor elem in &vec { // Iterate over each element in the array println!("{}", elem); } -
Adjust the size of the array: Use the
resizemethod to change the array size and specify a default value for new elements:rustvec.resize(10, 0); // Resize the array to 10 elements, initializing new elements to 0
The above steps demonstrate how to effectively use and manage dynamic arrays in Rust. Vec<T> provides various methods to support dynamic modification and access of arrays, making it the preferred way to handle dynamic arrays.