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 programs had loose variables. A real program bundles related data: a book has a title and page count, a user has a name and email. That's exactly what structs are for — Rust's version of a "record":
struct Book {
title: String,
pages: u32,
}
fn main() {
let b = Book {
title: String::from("Der Rust-Weg"),
pages: 312,
};
println!("{} hat {} Seiten", b.title, b.pages);
}
A struct literal names every field by name. If you forget one, the compiler immediately complains (E0063) — instead of creating a half-initialized object at runtime, as is possible in many languages.
struct Book {
title: String,
pages: u32,
}
fn main() {
let title = String::from("Kurze Note");
let pages = 2;
let note = Book { title, pages }; // Feld-Init-Kurzschreibweise
let book = Book {
pages: 312,
..note // REST aus note übernehmen
};
println!("{book:?}");
}
Two common tools: Book { title, pages } uses the variable with the same name (field-init shorthand). ..note takes over all remaining fields from another instance.
Debug for println! ({:?})
println!("{b:?}") prints the whole structure — for that, the type needs the Debug trait. You simply add #[derive(Debug)] above the struct definition and the compiler generates the output for you.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 3, y: -2 };
println!("{p:?}");
// → Point { x: 3, y: -2 }
}
Structs are Copy types only if all fields are Copy. As soon as a String field is involved, an assignment moves ownership — and with the update syntax ..base you move the non-Copy fields out of base ("partial move"). After that, base is consumed as a whole.
Check: What does this program output?
Answer: Point { x: 3, y: -2 }
With #[derive(Debug)], {:?} prints the fields with names: Point { x: 3, y: -2 }.
Takeaways:
⚠ Common mistake: Reassigning a field on a non-
mutbinding:b.pages = 400;fails withcannot assign to b.pages, as struct b is not declared as mutable— fields inherit mutability from the binding. Declare the instance aslet mut bfrom the start; selectively "unlocking" individual fields does not exist in Rust.
Data without behavior is only half useful. Methods go into an impl block — separate from the data, but associated with the type:
struct Counter {
count: u32,
}
impl Counter {
fn new() -> Self {
Counter { count: 0 }
}
fn increment(&mut self) {
self.count += 1;
}
fn value(&self) -> u32 {
self.count
}
}
fn main() {
let mut c = Counter::new();
c.increment();
c.increment();
println!("count = {}", c.value());
// → count = 2
}
The first parameter of a method decides what it may do with the instance:
| Receiver | Meaning | Typical for |
|---|---|---|
&self | borrows read-only | Calculating, reading, displaying |
&mut self | borrows mutably | Changing state like increment |
self | takes ownership | Consuming transformations, builders |
Counter::new has no self at all — it's an associated function (the classic constructor), called with Counter::new(). Self is the abbreviation for the type itself.
When which receiver?
Default question: Does the method need ownership? No → &self (read) or &mut self (change). self only if the caller consciously no longer needs the value afterward — the compiler enforces this for both sides.
Rust has no hidden this pointer: the method receives the instance explicitly as the first parameter. Method calls with dot syntax (c.increment()) dereference automatically — whether it's c, &mut c, or a box smart pointer behind it.
Check: How do you create a new Counter without an existing instance?
Answer: Counter::new() — associated function, no self needed
Functions in an impl block without a self parameter are associated functions and are called with the double colon: Counter::new().
Takeaways:
⚠ Common mistake: Declaring a state-changing method as
fn increment(&self)— inside it,self.count += 1;isE0596: cannot borrow self.count as mutable, as it is behind a & reference. Methods that mutate themselves need&mut self;&selfis a strict read-only promise to the caller.
Sometimes fields don't need names — the order is enough:
struct Meters(u32);
struct Seconds(u32);
fn main() {
let dist = Meters(120);
println!("{} Meter", dist.0); // Zugriff per Index
}
That's a tuple struct: Meters(120) looks like a function call and stores a u32 — but as a distinct type.
Meters and Seconds behave exactly like u32 in memory (same size, same speed). Nevertheless, the compiler cannot confuse them:
struct Meters(u32);
struct Seconds(u32);
impl Meters {
fn add(self, other: Meters) -> Meters {
Meters(self.0 + other.0)
}
}
fn main() {
let a = Meters(120);
let b = Meters(80);
println!("{} m", a.add(b).0);
// → 200 m
// a.add(Seconds(5)); // ❌ expected `Meters`, found `Seconds`
}
This pattern is called newtype and is ubiquitous in real Rust: IDs, units, versions — everything gets its own type, and "swapper" bugs become compile errors. Mars Climate Orbiter says hello.
struct WIP;
fn main() {
let _state = WIP;
}
A unit struct has no fields at all. It serves as a marker: the type ITSELF carries the information ("nothing in here yet") without costing a byte of data. Later in the course we'll see it again in state machines.
Check: Why is
a.add(Seconds(5))a compile error, even though both are u32?Answer: Because Meters and Seconds are different types — newtype prevents mixing
Newtypes are free at runtime, but distinct types at compile time. That's exactly their purpose: unit and ID mix-ups become impossible.
Takeaways:
⚠ Common mistake: Writing
Meters(120) + Meters(80)because there is au32inside — newtypes do not inherit operators, so you getE0369: cannot add Meters to Meters. Do the math on the inner value (a.0 + b.0) or via your own method likeadd; the+operator only exists once youimpl Add.
Time to bring it all together: an inventory of items with quantities — structs, Vec, methods, associated functions. First the scenario from working life:
Scenario: The Warehouse Management
You already have part of the scaffold from Lesson 14. The exercise lets you build the last part yourself — with the XP reward for solving it without help:
What you accomplished in Module 4
Takeaways:
⚠ Common mistake: Declaring the accumulator without
let mut:let sum = 0;followed bysum += item.qty;yieldsE0384: cannot assign twice to immutable variable sum. Rule of thumb for everytotal_count-style sum: the counter ismut, the items stay read-only via&self.items.
Course navigation: ← Module 3 · All 27 modules · Module 5 →