Sub topic 5
Common Vec methods: insert, remove, sort, dedup, retain
This chapter covers the Vec methods that change a vector in place. It assumes you know basic Rust syntax, ownership and borrowing, Option and match, and how to run programs with cargo. You should also know how to create a Vec and read from it.
The working model
Each method here takes &mut self, so the vector must be declared with mut. They change the vector directly and do not return a new one. Some return a value you may want, such as the element that was removed.
| Method | What it does | Returns |
|---|---|---|
| `sort()` | Orders elements ascending | nothing |
| `dedup()` | Removes consecutive duplicates | nothing |
| `retain(f)` | Keeps elements where `f` is true | nothing |
| `insert(i, x)` | Puts `x` at index `i`, shifting later items right | nothing |
| `remove(i)` | Takes out the item at `i`, shifting later items left | the removed item |
A worked example
fn main() {
let mut v = vec![5, 3, 8, 3, 1];
v.sort(); // [1, 3, 3, 5, 8]
v.dedup(); // [1, 3, 5, 8]
v.retain(|&x| x > 1); // [3, 5, 8]
v.insert(0, 2); // [2, 3, 5, 8]
let removed = v.remove(1); // removes 3
println!("{removed} {:?}", v); // 3 [2, 5, 8]
}The steps run in order, and each one acts on the result of the one before it.
Why the order matters
dedup only removes duplicates that sit next to each other. In [5, 3, 8, 3, 1] the two 3s are apart, so dedup alone would change nothing. Sorting first puts equal values side by side. This is the most common mistake with dedup.
retain takes a closure that receives a reference to each element. That is why the example writes |&x|, which pattern-matches the reference to get an i32. For non-Copy types, write |s| s.len() > 2 and use the reference as it is.
Panics and cost
insert(i, x) panics if i is greater than len(). An index equal to len() is allowed and appends. remove(i) panics if i is not less than len(). Both shift every later element, so they take time proportional to the number of elements after the index. Calling remove(0) in a loop on a large vector is slow.
If you do not need to keep the order, swap_remove(i) replaces the removed slot with the last element. It runs in constant time.
Sorting with sort() needs the element type to implement Ord. Floats such as f64 do not, because of NaN. Use sort_by with partial_cmp for floats, or sort_by_key to sort by a derived value.
fn main() {
let mut words = vec!["pear", "fig", "banana"];
words.sort_by_key(|w| w.len());
println!("{:?}", words); // ["fig", "pear", "banana"]
let mut temps = vec![21.5, 18.0, 25.25];
temps.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("{:?}", temps); // [18.0, 21.5, 25.25]
}Exercise
Exercise
Given let mut v = vec![4, 1, 4, 2, 1];, which calls produce [1, 2, 4], and why does v.dedup() alone not work?
Show answer
Calling v.sort(); and then v.dedup(); produces [1, 2, 4]. After sorting, the vector is [1, 1, 2, 4, 4], so equal values are adjacent and dedup removes the extras. dedup alone does nothing useful here, because it only removes consecutive duplicates and in [4, 1, 4, 2, 1] no equal values are next to each other.
Exercise
What does this program print? let mut v = vec![10, 20, 30, 40]; v.retain(|&x| x != 20); let r = v.remove(0); println!("{r} {:?}", v);
Show answer
It prints 10 [30, 40]. retain drops 20, leaving [10, 30, 40]. remove(0) returns 10 and leaves [30, 40].