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.
One function for every type variant? largest_i32, largest_char,
largest_string — three times the same code. Generics make the type a
parameter. But beware: without guarantees, not even a comparison compiles:
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut max = &list[0];
for item in list {
if item > max {
max = item;
}
}
max
// → 9
fn main() {
let zahlen = vec![3, 9, 4];
let zeichen = vec!['y', 'a', 'm'];
println!("{}", largest(&zahlen));
// → 9
println!("{}", largest(&zeichen));
}
The : PartialOrd is a trait bound — a promise to the compiler:
"any T with which you instantiate this function can be compared".
Without the bound, the line item > max would stop the compiler: it
doesn't know T's capabilities.
Structs can also be generic — with as many type parameters as fields need:
struct Point<T, U> {
x: T,
y: U,
}
fn main() {
let ganzzahlig = Point { x: 3, y: -2 };
let gemischt = Point { x: 1, y: 0.5 };
println!("{:?} und {:?}", ganzzahlig, gemischt);
}
The type of gemischt is inferred — the parameters T and U fill
themselves in automatically. And the best part: generics cost nothing
at runtime. The compiler generates a specialized copy for each concrete
type used (monomorphization) — the same machine code as if you had
written each function by hand.
Check: What does monomorphization achieve?
Answer: The compiler stamps out a specialized copy per concrete type — zero runtime cost
Static specialization at compile time: that's what 'zero-cost abstraction' means concretely.
Monomorphization vs. dynamic dispatch
Monomorphization is static dispatch: the compiler generates a separate function for each concrete type — at runtime there is no table, no indirection. This is the default path in Rust.
The alternative is dynamic dispatch with dyn Trait: a vtable (virtual
method table) at runtime. This costs one indirection call, but only one copy
of the function is compiled into the binary — regardless of how many types are
used.
// Static (monomorphization) — zero cost, larger binary
fn print_all<T: Display>(items: &[T]) { ... }
// Dynamic — one vtable, smaller binary, minimal runtime cost
fn print_all(items: &[Box<dyn Display>]) { ... }
Current research on meta-monomorphizing specialization (2026) investigates how compilers can optimize specialized code paths even more aggressively — with the goal of further shifting the trade-off between binary size and speed.
⚠ Common mistake: Writing
fn largest<T>(list: &[T])withoutT: PartialOrd— the compiler complains at>, because it doesn't know T is comparable.
Takeaways:
Generics say "some type". Traits say "some type that can DO THIS" — and define what THIS means. A trait is a contract of method signatures:
trait Summarize {
fn author(&self) -> &str;
fn title(&self) -> &str;
fn summary(&self) -> String {
format!("{} von {}", self.title(), self.author())
}
}
struct Article {
title: String,
author: String,
}
impl Summarize for Article {
fn author(&self) -> &str {
&self.author
}
fn title(&self) -> &str {
&self.title
}
}
fn notify(item: &impl Summarize) {
println!("Neu: {}", item.summary());
// → Neu: Rust im Browser von Tobias
}
fn main() {
let a = Article {
title: String::from("Rust im Browser"),
author: String::from("Tobias"),
};
notify(&a);
}
Three concepts in one example: summary has a body — a default
implementation that Article inherits without writing it.
impl Summarize for Article is the implementation of the contract.
And &impl Summarize in notify accepts any type that fulfills the
contract — Article today, a tweet tomorrow.
Trait bounds connect generics with behavior
fn notify(item: &impl Summarize) — short form for a generic parameterCheck: Article implements only author and title. Why may notify call item.summary()?
Answer: summary has a default implementation in the trait
Default methods come with the trait — whoever doesn't override them inherits them.
⚠ Common mistake: Only implementing the default methods of a trait — the required methods without defaults are missing. The compiler lists them all: implement them or delete the
impl.
Takeaways:
Much of the standard behavior comes from standard traits — usually via derive, sometimes by hand:
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Money {
euros: u32,
cents: u8,
}
fn main() {
let preis = Money { euros: 12, cents: 34 };
let rabatt = Money { euros: 9, cents: 99 };
println!("{preis:?}");
// → Money { euros: 12, cents: 34 }
println!("teurer: {}", preis > rabatt);
}
What each one brings:
| Trait | provides | via derive? |
|---|---|---|
| Debug | {:?} output | yes |
| Clone / Copy | duplicate / copy on assignment | yes |
| PartialEq / Eq | == and != | yes |
| PartialOrd / Ord | <, >, sorting | yes |
| Default | ::default() with zero values | yes |
| Hash | as HashMap key | yes |
| Display | {} output for users | by hand |
Display shows why "by hand": user output wants FORMAT — currency, decimal places, locale. No derive can guess that:
use std::fmt;
impl fmt::Display for Money {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{},{:02} €", self.euros, self.cents)
}
}
fn main() {
let m = Money { euros: 12, cents: 4 };
println!("{m}");
}
And From/Into — the Module 7 bridge tool: if you implement From, you get Into for free.
Check: Why can you derive Copy for Money, but not for a struct with a String field?
Answer: Copy requires Copy on all fields — String owns heap memory and is only Clone
Copy means bitwise duplication on assignment. A String pointer alone would be double-owned — hence Clone instead of Copy.
⚠ Common mistake: Deriving
Copyfor a struct with aStringfield — this doesn't work because String owns heap memory and only implementsClone.
Takeaways:
Time for a mini-project with production quality: a small statistics library. The trick is the API decision: mean and median return an Option — because an empty data series has no mean.
Scenario: The evaluation that lies
⚠ Common mistake: The
meanfunction returns0.0for empty input — the same problem as in the scenario. The API lies instead of usingOption<f64>.
What you accomplished in Module 8
Takeaways:
Course navigation: ← Module 7 · All 27 modules · Module 9 →