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)
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
| Parameter | Description |
|---|---|
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
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.
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.
Related
Iterator::map, filter and filter_map· Transform and select items lazily: map each item, keep matching ones, or do both at once with filter_map.slice contains, iter().position and binary_search· Search slices: membership, the index of a match, the first matching item, or a binary search in sorted data.- Rust Collections: Vec, HashMap and More · tutorial