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 classic that doesn't compile — and makes you fully grasp the most important concept in Rust:
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() {
x
} else {
y
}
}
The compiler rejects it (E0106: missing lifetime specifier). Why?
The return value comes sometimes from x, sometimes from y — the compiler cannot
know from reading the signature how long the results remain valid.
The solution: a lifetime annotation as a contract:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let s1 = String::from("long string");
let s2 = String::from("short");
let result = longest(s1.as_str(), s2.as_str());
println!("longer: {result}");
}
// → longer: long string
Read as: "'a denotes the span in which both inputs are valid — and the result
lives at most as long." Important: The annotation changes nothing at runtime.
It is purely compile-time documentation, against which the borrow checker measures
every call. If s2 hadn't outlived the block where result is used, the call would
have been rejected.
What lifetimes are — and what they are not
Check: Why does
fn longest(x: &str, y: &str) -> &strneed a lifetime parameter?Answer: So the compiler knows which input reference the output outlives
Without a lifetime annotation the compiler cannot verify that the returned reference lives long enough. The
'aannotation links the output to the inputs — pure compile-time information, no runtime cost.
⚠ Common mistake: "Fixing" E0106 by building a
Stringinside the function and returningresult.as_str()— the compiler rejects it with E0515 ("cannot return reference to temporary value"). An annotation can only connect input references to the output; it can never make a reference to local data valid, whatever you name it.
Takeaways:
Good news: In real code, lifetime annotations are rare. That's thanks to the elision rules — patterns that the compiler applies automatically:
&self, the output gets self's lifetimeThat's why this compiles without a single annotation:
fn first_word(s: &String) -> &str {
for (i, &b) in s.as_bytes().iter().enumerate() {
if b == b' ' {
return &s[0..i];
}
}
s.as_str()
}
fn main() {
let sentence = String::from("first word follows");
println!("first word: {}", first_word(&sentence));
}
// → first word: first
One input reference, one output — rule 2 connects them. That's exactly why
our functions from the last modules never had annotation baggage:
&str in, &str out, the checker silently validates every line.
You have to write explicitly when two inputs compete for the output —
like with longest.
Check: Why does first_word need no lifetime annotation?
Answer: Elision rule 2: one input reference provides the lifetime for the output
Elision is syntactic sugar for the most common cases — everything is still checked.
⚠ Common mistake: Confusing elision with "no lifetime checks". A method taking
&selfplus another reference parameter silently binds the output toself(rule 3) — if the return value actually comes from the other parameter, callers hit cryptic "borrowed value does not live long enough" errors. Only an explicit signature with a shared lifetime tells the compiler the truth.
Takeaways:
Structs own data — but they can also only borrow. If a struct holds a reference, it needs its own lifetime: every instance is bound to the borrowed data and dies with it.
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn new(text: &'a str, up_to: usize) -> Excerpt<'a> {
Excerpt {
part: &text[..up_to.min(text.len())],
}
}
}
fn main() {
let novel = String::from("Rust: safe and fast");
let ex = Excerpt::new(&novel, 4);
println!("Excerpt: {}", ex.part);
}
// → Excerpt: Rust
Excerpt<'a> means: "Excerpt No. 1 borrows from data that lives at least as long
as the excerpt is used." If you dropped novel and then read ex, the compiler
would stop you with E0505 — the original is gone before the excerpt needed it.
A special case deserves its name: 'static — the lifetime of the entire program run. String literals are the most common representative:
fn motto() -> &'static str {
"safe, fast, productive"
}
fn main() {
println!("{}", motto());
}
The literal lives in the binary file — it cannot "disappear", so the reference may live forever. Anything created at runtime (String::from, files, network) lives shorter and gets correspondingly shorter lifetimes.
When do I need 'a on a struct?
⚠ Common mistake: Omitting
'aon the struct —struct Excerpt { part: &str }does not compile; the compiler insists on a named lifetime parameter here. And the reflex of patching it with&'static strbackfires at the firstString::from: data created at runtime never satisfies'static, and E0597 ("borrowed value does not live long enough") follows. An ownedStringfield is often the more honest design.
Check: What does
'staticmean in Rust?Answer: The reference lives for the entire program duration
'static is the longest possible lifetime — the reference lives until the program ends. String literals are &'static str. It says nothing about thread safety.
Takeaways:
The final project of the module: a text workshop that works without a single copy — everything is slices into the original. To start, the scenario:
Scenario: The log analyzer
What you accomplished in Module 9
⚠ Common mistake: Grabbing
let longest = longest_line(&log);and then trying to keep writing tolog— as long as the slice reference is alive, the compiler refuseslog.push_str(...)with E0502 ("cannot borrow as mutable"). To analyze and append at the same time, turn the slices into owned values or finish the evaluation first.
Takeaways:
Course navigation: ← Module 8 · All 27 modules · Module 10 →