In Rust, dynamic arrays are typically created and managed using the Vec<T> type, where T represents the type of elements in the array. Vec<T> is a collection that can grow or shrink at runtime, similar to lists or vectors in other languages.
Creating a Vec
To create a new dynamic array in Rust, you can use the Vec::new() method or the vec![] macro to initialize a Vec with specific elements. For example:
rust// Using Vec::new() to create an empty Vec let mut numbers: Vec<i32> = Vec::new(); // Using vec! macro to initialize Vec let mut numbers = vec![1, 2, 3, 4, 5];
Adding Elements
To add elements to a Vec, you can use the push method. For example:
rustlet mut numbers = Vec::new(); numbers.push(10); numbers.push(20); numbers.push(30);
Removing Elements
To remove elements from a Vec, you can use the pop method (which removes and returns the last element) or the remove method to specify removing an element at a particular index. For example:
rustlet mut numbers = vec![10, 20, 30, 40]; numbers.pop(); // Removes 40 numbers.remove(1); // Removes 20, the element at index 1
Accessing Elements
To access elements in a Vec, you can use index-based access with the [] syntax. For safe access, you can use the get method, which does not cause the program to crash on index out-of-bounds errors but instead returns None. For example:
rustlet numbers = vec![10, 20, 30, 40]; println!("Second element: {}", numbers[1]); if let Some(first) = numbers.get(0) { println!("First element: {}", first); } else { println!("Index out of bounds"); }
Iterating Elements
To iterate over elements in a Vec, you can use a for loop:
rustlet numbers = vec![10, 20, 30, 40]; for number in numbers { println!("{}", number); }
Adjusting Size
You can also use the resize method to adjust the size of a Vec, increasing or decreasing the number of elements, and providing a default value for new elements. For example:
rustlet mut numbers = vec![1, 2, 3]; numbers.resize(5, 0); // Adjusts to 5 elements, new elements initialized to 0
These are some basic methods for creating and managing dynamic arrays in Rust. In practical development, it is important to choose the appropriate methods based on your needs when handling dynamic arrays.