IntermediateLesson 10 of 16
Vec, String & HashMap – Rust
The most important collections of the standard library and how Rust handles text.
Vec<T> is the growable list (heap array). You create it with vec![], access it safely with get (returns an Option), and risk a panic on an invalid index with [i].
fn main() {
let mut v = vec![3, 1, 2];
v.push(5);
v.sort();
println!("{:?} {} {:?}", v, v.len(), v.get(10)); // [1, 2, 3, 5] 4 None
v.retain(|&x| x != 2);
println!("{:?}", v); // [1, 3, 5]
let teil = &v[1..];
println!("{:?}", teil); // [3, 5]
}Rust has two text types: String (owns its content, mutable, heap) and &str (a borrowed view of text, e.g. string literals). Both are always valid UTF-8. That is why there is no index access like s[0]: characters can be several bytes long.
fn main() {
let mut s = String::from("Hello");
s.push_str(", World");
s.push('!');
println!("{s} {}", s.to_uppercase());
let woerter: Vec<&str> = "a b c".split(' ').collect();
println!("{:?}", woerter); // ["a", "b", "c"]
let t = "Élève";
println!("{} {}", t.len(), t.chars().count()); // 7 5 (bytes vs. characters)
let ganz = format!("{}-{}", "x", 5);
println!("{ganz}");
}HashMap<K, V> stores key-value pairs. The entry API is ideal for counting and grouping. The iteration order is unspecified; for sorted output, use BTreeMap.
use std::collections::HashMap;
fn main() {
let mut punkte: HashMap<&str, i32> = HashMap::new();
punkte.insert("Ada", 10);
punkte.insert("Bob", 7);
*punkte.entry("Ada").or_insert(0) += 5;
*punkte.entry("Cy").or_insert(0) += 1;
println!("{:?}", punkte.get("Ada")); // Some(15)
println!("{}", punkte.contains_key("Bob")); // true
let mut namen: Vec<_> = punkte.keys().collect();
namen.sort();
println!("{:?}", namen); // ["Ada", "Bob", "Cy"]
}TipOther collections:
HashSet (unique values), BTreeMap/BTreeSet (sorted), VecDeque (queue accessible from both ends), and BinaryHeap (priority queue).WarningA slice like
&s[0..2] on a string panics if the boundary falls in the middle of a character (e.g. with é). With accented letters, use chars() or char_indices().