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: atomic operations, memory orderings, and CAS loops — tools without locks but with sharper contracts. When atomics shine and when the mutex stays.
From Module 4 you know structs: all fields at once. An enum is the opposite: either/or. A value is exactly one of several variants — and each variant can carry its own data:
enum Shape {
Circle { radius: f64 },
Rectangle(f64, f64),
Point,
}
fn area(s: Shape) -> f64 {
match s {
Shape::Circle { radius } => 3.14159 * radius * radius,
Shape::Rectangle(w, h) => w * h,
Shape::Point => 0.0,
}
}
fn main() {
println!("{}", area(Shape::Circle { radius: 2.0 }));
// → 12.56636
println!("{}", area(Shape::Rectangle(3.0, 4.0)));
// → 12
}
Three variants, three different forms of data: struct-like (named fields), tuple-like (positions), and without any data. This is how you model "one of" without compromises.
Enums also get impl blocks with methods — the behavior belongs to the family, not to the individual variant:
enum Response {
Ok,
NotFound,
ServerError(String),
}
impl Response {
fn is_success(&self) -> bool {
matches!(self, Response::Ok)
}
}
fn main() {
let r = Response::ServerError(String::from("DB down"));
println!("{}", r.is_success());
}
matches! is a macro for the compact yes/no question: "Is this that variant?" For anything more detailed, use a real match.
Enum vs. Struct — the modeling question
HTTP responses are an enum (Ok OR NotFound OR ServerError); an HTTP response with headers and body would be a struct.
Check: What variant forms can a Rust enum have?
Answer: Mix of no data, tuple-like, and struct-like — per variant
Each variant chooses freely: Point (nothing), Rectangle(f64, f64) (tuple-like), Circle { radius } (struct-like).
Scenario: The status codes
⚠ Common mistake: Comparing with
==— sayif r == Response::Ok— only compiles once you add#[derive(PartialEq)]above the enum; otherwise the compiler rejects it witherror[E0369]: binary operation == cannot be applied to type Response. For a quick variant check without the derive, usematches!.
Takeaways:
The two most important enums in the whole language are standard: Option and Result. They replace null and exceptions — through types.
fn find_price(catalog: &[(&str, u32)], article: &str) -> Option<u32> {
for (name, price) in catalog {
if *name == article {
return Some(*price);
}
}
None
}
fn main() {
let catalog = [("Kaffee", 7), ("Tee", 4)];
match find_price(&catalog, "Tee") {
Some(price) => println!("Preis: {price}"),
None => println!("unbekannt"),
}
}
Option is Some(value) or None. There is no third way — and the compiler requires you to consider both cases before you get to the value. The billion-dollar mistake "null reference" does not exist in Rust.
fn parse_age(s: &str) -> Result<u32, String> {
match s.parse::<u32>() {
Ok(age) => Ok(age),
Err(_) => Err(String::from("keine gültige Zahl")),
}
}
fn main() {
println!("{:?}", parse_age("42"));
// → Ok(42)
println!("{:?}", parse_age("abc"));
// → Err("keine gültige Zahl")
}
Result<T, E> is Ok(T) or Err(E) — for everything that can and should fail: parsing, files, network. The caller CANNOT ignore the error without doing so explicitly.
Panic is not error handling
panic! aborts — for real bugs and broken invariants. Anything that can predictably go wrong (bad input, missing file) belongs in Result. unwrap() on an Err or None panics: good for tests and prototypes, taboo in production.
Check: Why is .unwrap() on a Result dangerous in production code?
Answer: It panics on Err — a handleable error becomes a crash
unwrap = 'give me the value or die'. In production, you propagate errors (next lessons) or handle them.
⚠ Common mistake: Writing a
matchwith only aSome(price)arm fails witherror[E0004]: non-exhaustive patterns: None not covered— withResult, the missing arm isErr(_). Both cases are mandatory; that is precisely the protection against null-style thinking. If only one case interests you, reach forif letdeliberately.
Takeaways:
match is more powerful than switch: patterns destructure, guards filter, bindings capture values. An overview of the tools:
fn classify(temp: i32) -> String {
match temp {
x if x < 0 => String::from("frost"), // Guard
n @ 0..=30 => format!("okay ({n} Grad)"), // Range + @-Binding
_ => String::from("heiß"),
}
}
fn main() {
println!("{}", classify(-5));
println!("{}", classify(21));
println!("{}", classify(35));
}
enum Message {
Move { x: i32, y: i32 },
Say(String),
Ping,
}
fn handle(msg: Message) {
match msg {
Message::Move { x, y } => println!("gehe zu {x},{y}"),
Message::Say(text) if text.len() > 20 => println!("langer Text"),
Message::Say(text) => println!("sage: {text}"),
Message::Ping => println!("pong"),
}
}
fn main() {
handle(Message::Move { x: 3, y: 7 });
handle(Message::Say(String::from("hallo")));
}
The pattern Move { x, y } takes the fields apart — without intermediate variables. A guard (if text.len() > 20) filters within an arm; the compiler still checks for exhaustiveness.
Exhaustiveness is the super concept
match MUST cover every case. If your team adds a variant tomorrow, every unadapted spot breaks at compile time — instead of silently running wrong at runtime. _ deliberately disables this check: use it for "the rest doesn't matter", never out of convenience.
Only ONE case matters? if let is the compact match:
fn main() {
let maybe = Some(42);
if let Some(n) = maybe {
println!("Wert: {n}");
}
let maybe2: Option<i32> = None;
let doubled = if let Some(n) = maybe2 {
n * 2
} else {
0
};
println!("{doubled}");
}
And since Rust 1.65 there is let ... else for early exit from the function when the interesting case is missing.
Check: What does
n @ 1..=12do in the pattern?Answer: Binds the whole value to n while the range is checked
The @-binding captures the complete value in n and tests it against 1..=12 at the same time — perfect for months, grades, menus.
⚠ Common mistake: All
matcharms must return the same type. If one arm yieldsString::from("frost")and another returns the literal"hot"as&str, you geterror[E0308]: match arms have incompatible types. Add.to_string()consistently — or returnStringfrom every arm.
Takeaways:
Option and Result have a whole toolbox of methods that replace match boilerplate — combinators:
fn main() {
let maybe: Option<i32> = Some(5);
// map: transform the value if present
println!("{:?}", maybe.map(|n| n * 2));
// unwrap_or / unwrap_or_else: fallback instead of panic
println!("{}", maybe.unwrap_or(0));
println!("{}", None::<i32>.unwrap_or_else(|| expensive()));
// ok_or: Option into Result with an error message
let r = maybe.ok_or(String::from("fehlt"));
println!("{r:?}");
}
fn expensive() -> i32 {
42
}
The big hit is the ? operator: "If Ok/Some, take the value. If not, leave the function IMMEDIATELY with the error."
fn parse_pair(s: &str) -> Result<(i32, i32), String> {
let (a, b) = s
.split_once(',')
.ok_or_else(|| String::from("Komma fehlt"))?;
let x = a.trim().parse::<i32>().map_err(|e| format!("x: {e}"))?;
let y = b.trim().parse::<i32>().map_err(|e| format!("y: {e}"))?;
Ok((x, y))
}
fn main() {
println!("{:?}", parse_pair("12, -3"));
// → Ok((12, -3))
println!("{:?}", parse_pair("7,x"));
// → Err("y: invalid digit found in string")
}
Three error sources, three ? — zero boilerplate. The error flow reads like the happy path, and every error message is intentional. map_err translates foreign error types into yours.
The rule for clean error flow
?, make them understandable with map_err.Check: What happens with
expr?when expr is an Err?Answer: The surrounding function returns immediately with the Err
? is early return: Ok → value, Err → function ends with that Err (possibly converted via From).
⚠ Common mistake: The
?operator only works inside functions that themselves returnResultorOption. In amainreturning()(or any other non-Result function) you geterror[E0277]: the ? operator can only be used in a function that returns Result or Option. Change the signature — or handle the error explicitly withmatch.
Takeaways:
Course navigation: ← Module 4 · All 27 modules · Module 6 →