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.
So far, your values lived on the stack — with known, fixed size. Box moves the content to the heap; on the stack only a thin pointer remains that owns the value:
fn main() {
let gross = Box::new([0u8; 4096]);
println!("erstes Byte: {}", gross[0]);
println!("Länge: {}", gross.len());
}
// → erstes Byte: 0
// Länge: 4096
Thanks to Deref, the Box pointer behaves like the value itself: index access, methods, dereferencing with * — everything works directly. On drop, the heap memory is freed. One owner, one release — your ownership model, just with a detour through the heap.
Two classic use cases:
use std::error::Error;
fn alter_von(zeile: &str) -> Result<u32, Box<dyn Error>> {
let (_, wert) = zeile
.split_once('=')
.ok_or("Zeile ohne Gleichheitszeichen")?;
Ok(wert.trim().parse::<u32>()?)
}
fn main() {
println!("{:?}", alter_von("alter=30"));
}
Box<dyn Error> is the pragmatic error type for programs: any concrete error type fits in, ? converts automatically.
When Box?
Check: When do you use
Box<T>instead of a reference&T?Answer: When I need data on the heap and own it exclusively
Box is a single owner on the heap — ideal for recursive types and trait objects. For shared ownership you need Rc/Arc, for runtime borrows RefCell.
⚠ Common mistake: Keep using a value after boxing it —
let boxed = Box::new(data);movesdata, and any later access todatafails with E0382 ("use of moved value"). A Box does not conjure up a second owner; it only relocates the one owner you have onto the heap. If you need the value afterwards, clone it first or borrow through&*boxed.
Takeaways:
Box has exactly one owner. But sometimes multiple need the same value: a configuration that two modules read; a node that multiple data structures point to. Rc (Reference Counted) allows multiple owners — counted at runtime:
use std::rc::Rc;
fn main() {
let konfig = Rc::new(vec![10, 20, 30]);
let kopie_a = Rc::clone(&konfig);
let kopie_b = Rc::clone(&konfig);
println!("a-Summe: {}", kopie_a.iter().sum::<u32>());
println!("Besitzer: {}", Rc::strong_count(&konfig));
}
// → a-Summe: 60
// Besitzer: 3
Rc::clone copies NOTHING — it only increments the counter. All three bindings point to the same heap value; when the last owner goes away, it is freed. strong_count tells you how many there are right now.
The price: Rc contents are read-only. With multiple owners, a change through one pointer could invalidate what another is currently reading — exactly what Rust's aliasing rule forbids. For mutation, you need the next building block.
And Rc stays at home: its counter is not atomic, so Rc is explicitly not thread-safe. For threads, there is Arc — the same pattern with an atomic counter (Module 12).
Check: What does Rc::clone(&konfig) cost at runtime?
Answer: A counter increment — the heap value is not copied
Rc::clone is intentionally cheap: increment counter, pass pointer. Deep copy would be .clone() on the value itself.
⚠ Common mistake: Calling mutating methods on the shared value — for instance
konfig.push(40)whenkonfigis anRcaround a vector. The compiler refuses with E0596 ("cannot borrow data in an Rc as mutable"), becauseRcimplements onlyDeref, notDerefMut. Shared means read-only — interior mutability arrives withRefCellin the next lesson.
Takeaways:
The borrow rules apply at compile time — usually good, sometimes too strict: a logger is shared by many places and still needs to grow. RefCell moves the check to runtime:
use std::cell::RefCell;
fn main() {
let log = RefCell::new(Vec::new());
log.borrow_mut().push(String::from("start"));
{
let lesend = log.borrow();
println!("Einträge: {}", lesend.len());
}
log.borrow_mut().push(String::from("ende"));
println!("{:?}", log.borrow());
}
// → Einträge: 1
// ["start", "ende"]
borrow() lends read-only (any number of times), borrow_mut() exclusively. The rule stays the same — Shared XOR Exclusive — only that RefCell counts it: a conflict panics immediately, with a precise message. The inner block returns the read borrow before borrow_mut() comes.
The combo of both worlds is the classic: Rc + RefCell — Rc shares ownership, RefCell allows mutation through the shared handle. Shared, mutable state without unsafe.
Runtime borrows under control
Check: What does
RefCellenable thatBoxcannot?Answer: Interior mutability at runtime despite an immutable reference
RefCell moves the borrow rule to runtime: borrow_mut() panics on conflict. Box checks at compile time. For thread-safe interior mutability you need Mutex/RwLock.
⚠ Common mistake: Holding a
borrow_mut()guard in a variable and callingborrow()in between — this compiles without complaint and panics only at runtime ("already mutably borrowed"). The borrow rule is unchanged; only its enforcement has moved to runtime. Scope borrows tightly, or usetry_borrow_mutwhen the conflict should be caught instead of crashing the program.
Takeaways:
The scenario first — then you build the solution:
Scenario: The expense list everyone can see
What you achieved in Module 11
⚠ Common mistake: Wiring back-references between shared nodes as plain
Rc— two nodes strongly referencing each other keep the counter above zero forever, and the memory is never freed: no error, no warning, just a leak. For back-links useRc::downgradeto aWeakand verify withupgradeon access. The compiler prevents data races — cycles you have to catch yourself.
Takeaways:
Course navigation: ← Module 10 · All 27 modules · Module 12 →