Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
The Vec is Rust's standard list: growing elements of the same type, stored contiguously on the heap:
fn main() {
let mut v = vec![3, 1, 4];
v.push(1);
v.push(5);
println!("{} elements", v.len());
println!("second: {}", v[1]);
println!("{v:?}");
// → [3, 1, 4, 1, 5]
}
vec![...] builds the list. Internally, a Vec holds a triple of pointer, length, and capacity; when it grows beyond capacity, the buffer is reallocated and copied — push remains amortized cheap.
fn main() {
let v = vec![10, 20, 30];
match v.get(10) {
Some(x) => println!("found: {x}"),
None => println!("not there"),
}
}
v[10] panics on out-of-bounds access. v.get(10) returns Option<&T> — the same philosophy as in Module 5: absence is a value, not a crash.
fn main() {
let v = vec![1, 2, 3];
for x in &v {
print!("{x} "); // borrows — v remains usable
}
println!();
let sum: i32 = v.iter().sum();
println!("Sum: {sum}, v: {v:?}");
}
&v borrows the list for reading; v (without &) would move it into the loop. And for filtering in place, there's retain — instead of deleting while iterating (which the borrow checker would forbid):
fn main() {
let mut v = vec![3, -1, 4, -5];
v.retain(|&x| x >= 0);
println!("{v:?}");
}
⚠ Common mistake:
for x in vmoves the Vec into the loop — any later use, such asv.len(), fails witherror[E0382]: borrow of moved value: v. Iterate over&vorv.iter()when reading; the move is only right when you truly don't need the Vec afterwards.
Takeaways:
Key to value: HashMap<K, V> is the standard associative list.
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<String, i32> = HashMap::new();
scores.insert(String::from("anna"), 42);
scores.insert(String::from("ben"), 17);
println!("{:?}", scores.get("anna"));
// → Some(42)
scores.insert(String::from("anna"), 50); // overwrites
println!("{:?}", scores.get("anna"));
// → Some(50)
}
insert overwrites existing values and returns the old one as an Option. get returns Option<&V> — missing is a normal case.
The classic — word counter without double lookup:
use std::collections::HashMap;
fn word_counts(text: &str) -> HashMap<&str, u32> {
let mut counts = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
counts
}
fn main() {
let counts = word_counts("red green red blue green red");
for (word, n) in &counts {
println!("{word}: {n}");
}
}
entry(word) gets or creates the slot in one hash lookup, or_insert(0) seeds missing counters with 0 — and the returned &mut u32 you increment directly. Without entry you'd need contains_key plus get plus insert: three lookups where one suffices.
When entry instead of insert?
insert = "Set exactly this value" (fallback value is lost). entry = "Take the existing slot and work on it" — counting, appending, conditional insertion. The HashMap guarantees: exactly one value per key.
⚠ Common mistake:
counts.entry(word).or_insert(0) += 1;without the asterisk doesn't compile —or_insertreturns a&mut u32reference, and+=needs the value behind it:*counts.entry(word).or_insert(0) += 1;. Otherwise the compiler reportserror[E0368]: binary assignment operation += cannot be applied to type &mut u32.
Takeaways:
Not every question needs a value — some only need membership: "Have I seen this before?" That's what the HashSet is for:
use std::collections::HashSet;
fn deduped(values: &[i32]) -> Vec<i32> {
let unique: HashSet<i32> = values.iter().copied().collect();
let mut result: Vec<i32> = unique.into_iter().collect();
result.sort();
result
}
fn main() {
println!("{:?}", deduped(&[4, 2, 4, 1, 2, 9]));
// → [1, 2, 4, 9]
}
Insert O(1), containment O(1), no duplicates — ideal for sets, blacklists, already-seen markers.
Why are HashMap keys often String instead of &str? Because the owning String gives the map control over the lifetime — and lookups still work with literals:
use std::collections::HashMap;
fn main() {
let mut cap: HashMap<String, String> = HashMap::new();
cap.insert(String::from("de"), String::from("Hallo"));
cap.insert(String::from("en"), String::from("Hello"));
// &str lookup thanks to the Borrow trait:
println!("{:?}", cap.get("de"));
}
Rule: key requirements are Eq + Hash. For sorted iteration and range queries, there's the BTreeMap — same API, tree instead of hash, thus always in key order.
The collection choice in 10 seconds
HashMap<K, V>BTreeMap<K, V>Check: You need each term of a text exactly once, order doesn't matter. What do you use?
Answer: A HashSet — it stores each value at most once
HashSet guarantees uniqueness at O(1) — the Vec would need O(n) per check, the HashMap counts counters that don't interest you.
⚠ Common mistake: A HashSet has no defined order — iteration order can change between program runs. If you need deduplicated values in sorted form, call
sort()explicitly after collecting them, exactly like the example above. Never rely on a HashSet's output order.
Takeaways:
The final project of Module 6 combines HashMap, Vec, sorting, and the entry idiom into a classic of practical computer science:
Scenario: The vocabulary app
What you achieved in Module 6
⚠ Common mistake: Sorting the key without lowercasing first puts
Lagerandregalinto different groups —to_lowercase()before sorting is part of normalization, not an optional extra. Also,word.chars().sort()doesn't exist — collect withcollect::<Vec<_>>(), thensort(), then build theStringkey.
Takeaways:
Course navigation: ← Module 5 · All 27 modules · Module 7 →