Rust 1.99 (2024 edition) reference · Vec and HashMap

Rust Vec: push, pop, retain, dedup and sort Method

Grow and shrink vectors, remove items by condition, deduplicate, and sort, including by key or float values.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

fn push(&mut self, v: T)   fn retain<F>(&mut self, f: F)   fn sort(&mut self)   fn sort_by_key<K, F>(&mut self, f: F)

Parameters

ParameterDescription
push / pop / insert / remove Add and remove.
retain(|x| ...) Keep matching items.
sort / sort_by_key / sort_by Sort in place.
dedup Remove consecutive duplicates.
extend / drain Add many / take a range out.

Examples

Example 1
fn main() {
    let mut v = vec![5, 3, 8, 3, 1];
    v.push(9);
    let last = v.pop();
    v.sort();
    v.dedup();
    v.retain(|&x| x > 2);
    println!("{v:?} popped {last:?}");
}

Output

[3, 5, 8] popped Some(9)

Run this on your computer — see “Get Started” for setup.

Sorting floats and by key
fn main() {
    let mut orders = vec![("ana", 42.0_f64), ("ben", 15.5), ("cy", 99.9)];
    orders.sort_by(|a, b| b.1.total_cmp(&a.1));
    println!("{orders:?}");
    let mut words = vec!["pear", "fig", "banana"];
    words.sort_by_key(|w| w.len());
    println!("{words:?}");
}

Output

[("cy", 99.9), ("ana", 42.0), ("ben", 15.5)]
["fig", "pear", "banana"]

Run this on your computer — see “Get Started” for setup.

Was this page helpful?