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.
Every value has exactly one owner. When the owner goes out of scope, the value is dropped (memory freed, no garbage collector). What happens on assignment?
fn main() {
let s1 = String::from("hello");
let s2 = s1; // MOVE: s2 now owns the heap data
// println!("{s1}"); // ❌ E0382: value borrowed after move
println!("{s2}");
// → hello
}
String manages a heap buffer. Instead of secretly copying it, Rust moves the responsibility to s2 — s1 is then off-limits. This eliminates double-free and use-after-free at compile time.
fn main() {
let a = 5;
let b = a; // i32: Copy — simple copy
println!("{a} {b}"); // 5 5 — both valid
}
Integers, floating-point numbers, bool, char, and tuples of these implement Copy: assignment copies bitwise, the original remains valid. Anything with heap involvement (String, Vec, ...) moves.
fn consume(s: String) {
println!("{s}");
} // s is dropped here — memory freed
fn main() {
let s = String::from("hi");
consume(s); // ownership moves into the function
// consume(s); // ❌ E0382 — s is gone
}
If you want to keep the value: consume(s.clone()) (explicit deep copy) or better — next lesson — just borrow.
The three ownership rules
Scenario: Passing the config around
Check: What happens with
let s2 = s1;whens1is aString?Answer: s2 owns the buffer, s1 is now invalid (move)
String is not a Copy type. Assignment moves ownership to s2; s1 is off limits afterward (E0382). Copy types like i32 copy instead.
Takeaways:
⚠ Common mistake: Touching
s1again afterlet s2 = s1;is fine fori32because Copy types really do copy — forStringit'sE0382: borrow of moved valueinstead. The reflex that=copies the value comes from languages with silent deep copies; in Rust, assignment moves ownership for heap types.
Instead of giving up ownership, you borrow a value:
fn len(s: &String) -> usize { // & = only borrow
s.len()
} // The loan ends — nothing is dropped
fn main() {
let s = String::from("rust");
let n = len(&s);
println!("{s} hat {n} Bytes"); // ✅ s still belongs to us
// → rust hat 4 Bytes
}
At any point in time: either any number of immutable references &T, or exactly one mutable &mut T. Never both at the same time.
fn main() {
let s = String::from("hello");
let r1 = &s;
let r2 = &s; // ✅ many shared loans are fine
println!("{r1} {r2}");
}
fn main() {
let mut s = String::from("hi");
let a = &mut s;
let b = &mut s; // ❌ E0499: cannot borrow as mutable more than once
println!("{a}{b}");
}
Why this strictness? A writer alongside many readers would be a data race waiting to happen. The rule makes whole classes of errors impossible — at compile time, with no runtime cost.
fn main() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
let r3 = &mut s; // ❌ E0502 — r1/r2 are still read afterward
println!("{r1} {r2} {r3}");
}
Borrows don't live until the end of the scope, but until their last use (Non-Lexical Lifetimes, since Rust 2018):
fn main() {
let mut s = String::from("hello");
let r = &s;
println!("{r}"); // last use of r — loan ends here
s.push_str(" world"); // ✅ therefore legal
println!("{s}");
}
And the classic: clear() while word is still borrowing:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // ❌ E0502 — word is still read underneath
println!("{word}");
}
The borrow checker forbids you here from accidentally keeping a pointer to scrubbed data. In C, that would be a silent bug.
Readers or writers — never both
Allowed simultaneously: &T any number of times or &mut T exactly once. References must always remain valid (no dangling). That's the entire core rule of the borrow checker — everything else is details.
Check: How many
&mutreferences to the same value may exist at the same time?Answer: Exactly one
The aliasing rule: either many & or exactly one &mut, never both at once. Two &mut is E0499; & mixed with &mut is E0502.
Takeaways:
⚠ Common mistake: Reading NLL as a blank cheque: the loan ends at the last use, not just whenever. If
r1is used even once afterlet r2 = &mut s;— say, only at the very end inprintln!("{r1}")—E0502fires; "but I'm only reading" saves no one.
A slice is a view (fat pointer: pointer + length) into existing data — no copying:
fn main() {
let s = String::from("hello world");
let w = &s[0..5]; // &str — borrows the first 5 bytes
println!("{w}"); // hello
// → hello
}
&str is the universal string type for reading: string literals are &str, and &String is automatically converted to &str (deref coercion). That's why you use &str in function parameters, not &String:
fn greet(name: &str) -> String {
format!("Hello, {name}!")
}
fn main() {
greet("Rust"); // &str literal
let owned = String::from(" YOU ");
greet(&owned); // &String → &str — coercion
}
As a parameter: &str — the caller can pass literals, slices, and String alike. String as a parameter forces ownership transfer or cloning, &String excludes literals — both worse.
Slice = pointer + length
A &str doesn't copy bytes, it points into them. That's why the returned first_word reference is tied to the lifetime of the original string — for that, lifetime annotations are needed later (Module 9).
Check: What is the type of
&s[0..3]whensis aString?Answer: &str — a reference (fat pointer) into the original buffer
A slice is &str: pointer + length, no separate heap buffer. The bytes are borrowed, not copied. That's why the reference is tied to the original's lifetime.
Takeaways:
⚠ Common mistake: Slicing by byte index as if those were characters:
&name[0..5]on"Grüße"lands inside the two-byteßand panics withbyte index 5 is not a char boundary. To work character-wise, uses.chars()orchar_indices, not byte offsets.
Rust errors are teaching material. The four from this module:
| Code | Meaning | typical cause |
|---|---|---|
E0382 | use of moved value | value used after moving |
E0499 | cannot borrow as mutable more than once | two &mut at the same time |
E0502 | cannot borrow as mutable because also borrowed as immutable | & alongside &mut |
E0106 | missing lifetime specifier | function returns a reference to a soon-to-be-dropped value |
Strategy when reading:
help:) often anticipates a concrete fix.Check: What does E0502 mean?
Answer: Borrowing immutably and mutably at the same time
E0502 = aliasing violation: a shared loan is still alive while &mut is taken. E0382 is the move error, E0106 the lifetime message, E0499 double &mut.
Takeaways:
⚠ Common mistake: Blindly accepting the
help:line and sprinklingclone()at every error site — that clears theE0382symptoms without answering the actual design question (copy, or just borrow?). Read the first error in full and fix the cause; the rest are usually only fallout.
Course navigation: ← Module 2 · All 27 modules · Module 4 →