Vec::len() / is_empty() / contains() / get()
Rust's Vec provides a variety of useful methods for getting the element count, searching, and safe access. Common ones include len(), is_empty(), contains(), and get().
Syntax
let v = vec![10, 20, 30, 40, 50]; // Returns the number of elements. let len = v.len(); // 5 // Returns whether the Vec is empty. let empty = v.is_empty(); // false // Checks whether an element is present. let has = v.contains(&30); // true (passes a reference) // Safe index access (returns Option<&T>). let x = v.get(2); // Some(&30) let y = v.get(10); // None (out of bounds) // Accesses the first and last elements as references (Option<&T>). let first = v.first(); // Some(&10) let last = v.last(); // Some(&50) // Finds the first element that satisfies the condition. let found = v.iter().find(|&&x| x > 25); // Some(&30) // Returns the index of the first element that satisfies the condition. let idx = v.iter().position(|&x| x == 30); // Some(2)
Method List
| Method | Description |
|---|---|
| v.len() | Returns the number of elements in the Vec. |
| v.is_empty() | Returns whether the Vec is empty. |
| v.contains(&x) | Returns true if the value x is present. |
| v.get(i) | Returns the element at index i as Option<&T>. |
| v.get_mut(i) | Returns the element at index i as Option<&mut T>. |
| v.first() | Returns the first element as Option<&T>. |
| v.last() | Returns the last element as Option<&T>. |
| v.iter().find(|x| condition) | Returns the first element that satisfies the condition as Option<&T>. |
| v.iter().position(|x| condition) | Returns the index of the first element that satisfies the condition as Option<usize>. |
| v.iter().any(|x| condition) | Returns true if at least one element satisfies the condition. |
| v.iter().all(|x| condition) | Returns true if all elements satisfy the condition. |
| v.windows(n) | Returns an iterator over overlapping slices of n elements. |
| v.chunks(n) | Returns an iterator over non-overlapping slices of n elements each. |
Sample Code
fn main() {
let v = vec![10, 20, 30, 40, 50];
// Basic metadata.
println!("len: {}", v.len());
println!("is_empty: {}", v.is_empty());
let empty: Vec<i32> = vec![];
println!("empty Vec.is_empty: {}", empty.is_empty());
println!();
// Check for presence with contains.
println!("contains 30: {}", v.contains(&30));
println!("contains 99: {}", v.contains(&99));
println!();
// Safe access with get.
println!("v.get(2) = {:?}", v.get(2)); // Some(&30)
println!("v.get(5) = {:?}", v.get(5)); // None (out of bounds)
// Get a mutable reference with get_mut.
let mut v2 = vec![1, 2, 3, 4, 5];
if let Some(x) = v2.get_mut(2) {
*x = 99; // Modify the value at index 2.
}
println!("after get_mut: {:?}", v2);
println!();
// Access the first and last elements with first / last.
println!("first: {:?}", v.first());
println!("last: {:?}", v.last());
println!();
// Searching with iterator methods.
let found = v.iter().find(|&&x| x > 25);
println!("first value greater than 25: {:?}", found);
let idx = v.iter().position(|&x| x == 40);
println!("index of 40: {:?}", idx);
// Checking conditions with any / all.
println!("any element greater than 50: {}", v.iter().any(|&x| x > 50));
println!("all elements greater than 0: {}", v.iter().all(|&x| x > 0));
println!();
// windows (overlapping window slices).
let w: Vec<&[i32]> = v.windows(3).collect();
println!("windows(3): {:?}", w);
// chunks (n elements at a time).
let c: Vec<&[i32]> = v.chunks(2).collect();
println!("chunks(2): {:?}", c);
}
Notes
Knowing when to use get() versus index access (v[i]) is important. Use index access when the index is guaranteed to be in range, and use get() for user input or dynamic indices where safety matters.
The argument to contains() is a reference to the value (&x), which allows the comparison to be done without copying. Note that linear search on a large Vec is O(n), so consider using a HashSet or BTreeSet when fast lookup is needed.
Index access via v[i] will panic if the index is out of bounds. Always use get() when you cannot guarantee the index is valid.
For creating a Vec, see Vec::new() / vec![]. For sorting and removing duplicates, see Vec::sort() / dedup() / extend().
If you find any errors or copyright issues, please contact us.