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.
Porting practice: migrating C++/Java to Go — mapping catalog, errors as values instead of exceptions, porting concurrency (threads → goroutines) and securing the port.
Millions of lines of C++ run in production systems — office suites, browser engines, databases, game engines. Making all of it memory-safe is the dream; Rust is the answer. But how do you get there?
Research has gone through three waves:
The key takeaway for you as a translator: translation is an architecture project, not a syntax project.
The basic idea of any migration is simple: every C++ construct has a Rust counterpart. Fall back on this all the time:
| C++ | Rust | Meaning |
|---|---|---|
std::unique_ptr<T> | Box<T> | exclusive ownership |
std::shared_ptr<T> | Rc<T> / Arc<T> | shared ownership |
std::vector<T> | Vec<T> | dynamic array |
std::string | String / &str | text (UTF-8, not a byte array) |
std::map<K,V> | BTreeMap<K,V> / HashMap | sorted / hashed |
| exceptions | Result<T,E> + ? | errors as data |
nullptr | Option<T> | absence is a type |
| inheritance + virtual | enum + match | sum types, exhaustive |
| templates | generics + traits | bounds instead of implicit assumptions |
std::mutex | Mutex<T> | guarded state |
co_await | .await | explicit async |
| destructor (RAII) | Drop + ownership | enforced by the compiler |
// REMEMBER: ownership is explicit in Rust. Whoever builds a Vec<DocumentOp>
// needs no destructor, no unique_ptr, no delete.
// The compiler frees everything automatically at the end of the scope.
fn consume(ops: Vec<DocumentOp>) {
for op in ops { /* ... */ }
} // Cleaned up here — automatically.
Check: Why does literal (1:1) translation of C++ to Rust fail, according to the Fallacy study?
Answer: Because literal translation preserves the C++ architecture including its design bugs — the code is memory-safe, but not better.
The Fallacy study shows: memory safety is only half the battle. The bugs were in the design. Translation is an architecture project.
⚠ Common mistake: Translating C++ exceptions into
unwrap()orpanic!— the code compiles, but the first invalid input takes production down. Errors are values in Rust: every throw/catch becomesResult<T, E>plus?, and panics stay banned from library code.
Translation is an architecture project
C++ class hierarchies with virtual are the classic: a base class, polymorphic
behaviour, and every new subclass must be wired into every virtual method.
In Rust you translate this as a sum type (enum):
match — no forgotten case is possible.apply and undo sit side by side and are
maintained together.delete discipline.The classic example from document engines: a history of operations with undo — polymorphic via a pointer collection in the C++ original.
C++ (the old way, pointer soup):
class DocumentOp { public: virtual void apply(Document* d) = 0; virtual void undo(Document* d) = 0; };
class InsertOp : public DocumentOp { /* ... */ };
class DeleteOp : public DocumentOp { /* ... */ };
// OpHistory: std::vector<DocumentOp*> + manual delete in the destructor.
Rust (the new way, sum type):
enum DocumentOp {
Insert { pos: usize, text: String },
Delete { pos: usize, len: usize },
Style { pos: usize, style_id: u32, prev: u32 },
}
impl DocumentOp {
fn apply(&self, doc: &mut Document) -> Result<(), HistoryError> {
match self {
DocumentOp::Insert { pos, text } => doc.insert(*pos, text),
DocumentOp::Delete { pos, len } => doc.delete(*pos, *len),
DocumentOp::Style { pos, style_id, prev } => {
doc.set_style(*pos, *style_id)?;
Ok(())
}
}
}
fn undo(&self, doc: &mut Document) -> Result<(), HistoryError> {
// Iterate backwards — and every variant must be handled.
match self {
DocumentOp::Insert { pos, .. } => doc.delete(*pos, /*preview*/ 0),
DocumentOp::Delete { pos, len } => doc.reinsert(*pos, *len),
DocumentOp::Style { pos, prev, .. } => doc.set_style(*pos, *prev),
}
}
}
enum is more than a rename. The variants carry data with them
(text, style_id, prev), and match forces full coverage.
A new operation kind? Add it — and the compiler shows you every place you
must handle it. That is the biggest single source of truth Rust gives you.
// Pattern for closed behaviour sets:
enum Transition {
Idle, Draft, Published,
}
impl Transition {
fn next(&self) -> Option<Self> {
match self {
Transition::Idle => Some(Transition::Draft),
Transition::Draft => Some(Transition::Published),
Transition::Published => None, // exhaustive — no else, no C++ default-branch trap
}
}
}
Check: What does a sum type (enum + match) force when you add a new variant?
Answer: The compiler forces you to handle the new variant in every match — nothing is forgotten.
match is exhaustive: if an arm is missing, compile error. Virtual-dispatch class hierarchies cannot guarantee that.
⚠ Common mistake: Adding a
_ =>catch-all arm to everymatchout of C++default:habit — that erases the exhaustiveness guarantee: a new variant compiles silently and is silently ignored instead of making the compiler scream at every forgotten site. Skipping the default arm is the whole point of the sum type.
Inheritance → enum + match
After inheritance comes the hard part: the memory model. In C++ everything
was a pointer, and someone eventually called delete (or not). In Rust you
state explicitly who owns what. Three classic translation fights and their
solutions:
Open callbacks (signal/slot, observers) stash &mut handles in structs — normal
in C++, forbidden in Rust. Solution: pass &mut T down the call path
instead of hiding handles somewhere. Like this:
// C++ habit: this struct "owns" a pointer to the Document.
// Rust: do not store it at all — pass it through as a parameter.
fn render_all(doc: &mut Document) {
for section in doc.sections() {
render_section(doc, section); // one &mut, cleanly passed down
}
}
C++ pattern: a std::vector<T*> into the same arena the struct points to.
That is not allowed in Rust (the object would point to itself).
Solution: store usize ids instead of references and resolve them under a
single &mut borrow.
struct Arena {
items: Vec<Item>,
active: Option<usize>, // id instead of &Item
}
impl Arena {
fn activate(&mut self, id: usize) {
if let Some(item) = self.items.get_mut(id) {
item.hit_count += 1; // lookup under one &mut — rules respected
}
}
}
The C++ observer with std::function lists becomes a channel
(tokio::sync::watch/mpsc) in Rust. Events are data streams then, and
producers/consumers are cleanly separated by ownership — exactly what callbacks
pretend to be able to do but never guarantee.
// Producer/callback replacement: one sender/receiver pair.
let (tx, mut rx) = tokio::sync::mpsc::channel(16);
// Worker produces events; the UI consumes them — no shared state.
tx.send(Event::StyleChanged { pos: 12 }).await?;
C++ exceptions interrupt control flow and can "throw away" anything. In Rust
an error is a value (Result<T, E>) that must be handled explicitly.
Parsing user data? Always Result — never panic! in library code.
fn parse_size(s: &str) -> Result<usize, ParseError> {
let n: usize = s.trim().parse().map_err(ParseError::InvalidNumber)?;
Ok(n)
}
// → parse_size(" 42 ") returns Ok(42) — whitespace trimmed, number parsed
Check: How do you resolve a self-referential struct (C++: arena with pointers to itself) in Rust?
Answer: Store usize ids instead of references and resolve them under a single &mut.
Ids + lookups under one &mut avoid the self-reference problem without unsafe. Rc/RefCell is the C++ pointer-thinking reflex and usually the wrong answer.
⚠ Common mistake: The
Rc<RefCell<T>>reflex from C++ pointer thinking — parking a&muthandle in a struct (observer, callback) ends in E0499 ("cannot borrow as mutable more than once"), and wrapping everything inRc<RefCell>only moves the problem. Pass&mutdown the call path, resolve self-referential structures withusizeids, and turn callbacks into channels.
Pointers become ownership
The practice from industry (and the Ship-of-Theseus method): you translate one component, keep the seam (FFI), ship it — and repeat. The system stays runnable the whole time. For that you need two bridges:
Rust can expose a C ABI as a dynamic library:
# Cargo.toml — Rust library with C ABI
[lib]
crate-type = ["cdylib"]
#[no_mangle]
pub extern "C" fn wo_convert(src_ptr: *const u8, src_len: usize,
dst: *mut Vec<u8>) -> i32 {
// C++ calls this function through the generated C header.
let input = unsafe { std::slice::from_raw_parts(src_ptr, src_len) };
match convert(input) {
Ok(out) => { unsafe { *dst = out; } 0 }
Err(_) => -1,
}
}
// → 0 on a valid buffer (dst holds the result), -1 otherwise
bindgen generates Rust bindings from C/C++ headers; for large, living
boundaries cxx is the better choice — it generates both sides (C++ and
Rust code) from one shared declaration file and gives you type-safe,
non-unsafe calls:
// with cxx: safe calls to C++ methods, no unsafe in the calling code
let doc = ffi::wo_document_open(path)?;
doc.insert_paragraph(12); // cxx-generated, type-safe boundary
Every FFI boundary is a security boundary. Translated code containing
unsafe needs: (1) a comment naming the exact invariant, (2) a test that
breaks if the invariant is violated. Your goal: with each migration step the
number of unsafe sites becomes smaller than the number of pointer casts
the C++ had.
// Rule: unsafe is a gate, not a tool.
// Invariant: src_len == len of valid buffer at src_ptr (guaranteed by C++ caller).
// Test: wo_convert with a too-short buffer → -1, no UB (checked via Miri/Kani).
Check: What is the core idea of the Ship-of-Theseus method for migration?
Answer: Translate component by component; every seam runs over FFI, the system stays runnable at all times.
Ship of Theseus: replace piece by piece, keep the seam (FFI), ship, continue. No giant rewrite, no long phase without a shippable state.
⚠ Common mistake: Forgetting
#[no_mangle]— Rust then exports the symbol under a decorated name and the C++ linker fails with "undefined reference towo_convert" even though the function exists exactly like that. Check the seam forextern "C"on the signature andcrate-type = ["cdylib"]in Cargo.toml as well.
Never big-bang, always component by component
The biggest misconception of migration: "It compiles with the borrow checker,
so it's safe." The borrow checker guarantees memory safety of safe code —
not that your translation behaves correctly. Therefore: every translated
unit needs tests — round-trip tests (compare C++ output → Rust output) and
error-path tests (invalid input → Err, no panic).
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip_docx_to_html_keeps_paragraphs() {
let html = convert(b"<w:p>Hello world</w:p>").unwrap();
assert!(html.contains("Hello world")); // content survives, not exact formatting
}
#[test]
fn empty_input_yields_error_not_panic() {
assert!(convert(b"").is_err());
}
}
// cargo test:
// → test roundtrip_docx_to_html_keeps_paragraphs ... ok
// → test empty_input_yields_error_not_panic ... ok
When you want to actually prove the acceptance criteria (not just test them):
unsafe seams.requires/ensures
annotations become mathematical proofs.That is the point where translation becomes as safe as the C library never was — and as fast as Rust promises.
// The difference:
// cargo test → "these cases pass"
// cargo kani → "there is no input value that panics"
// verus → "the function fulfills its contract for ALL inputs"
Rc<RefCell> reflex?len()?unsafe: justified, named, tested — and less than the C++?If you meet all seven, this is no longer a translation — it is a rebirth. Congratulations, you have mastered migration.
Check: Why is the borrow checker alone not sufficient as proof of a successful translation?
Answer: It only checks memory safety — not whether the translation has the right behaviour.
Borrow checker: memory safety. Behaviour you prove with round-trip/error-path tests and, beyond that, with Kani/Verus.
⚠ Common mistake: Carrying byte offsets straight from the C++ code onto
&str—Stringis UTF-8, and a&text[..5]landing inside a multi-byte character panics with "byte index 5 is not a char boundary" even though everything compiles. Check length-derived indices withchar_indices()first or switch to iterators.
Verify, don't trust
Course navigation: ← Module 24 · All 27 modules · Module 26 →