Migration, interop & safety guarantees: how to port C++ code to Rust — sum types instead of inheritance, ownership transfer, cxx/bindgen, incremental Ship-of-Theseus migration and verifying what you translated.
Migration, interop & safety guarantees: how to port C++ code to Rust — sum types instead of inheritance, ownership transfer, cxx/bindgen, incremental Ship-of-Theseus migration and verifying what you translated.
Most toolkits store the entire UI state (hierarchy of widgets, text, colors) and
only ask you: "What should change?" — that is Retained Mode.
Egui does the opposite: every frame you rebuild the entire UI — Immediate Mode.
With every ui.label("Hello") immediately happen: layout management, mouse
interactions, rendering. No widget tree, no parent-child productions, only code
that reflects the current state.
Why this fits Rust perfectly:
&mut self). Retained mode toolkits hide their state inside Rc<RefCell<…>> —
with egui, everything stays explicit and type-safe.// Retained Mode is found in most GUI frameworks:
// 1. Define tree: let button = Button::new("Click"); window.add(button);
// 2. Keep tree alive: window.show();
// — the toolkit stores the tree between frames and only asks for changes.
// egui / Immediate Mode:
// Every frame the entire UI state is recreated by code.
| Criterion | Immediate Mode (egui) | Retained Mode (iced/Slint/Druid) |
|---|---|---|
| Simple UI, fast iteration | ✅ Ideal | ⚠️ Overhead |
| Complex hierarchies | ⚠️ Performance check | ✅ Natural |
| State management | ✅ Rust's &mut & Ownership | ⚠️ Rc/RefCell typical |
| Animations / dynamic UIs | ✅ Fresh frame each time | ✅ Good |
| Compile-time safety | ✅ Full type checking | ⚠️ Lifecycle complexity |
Check: Which description fits Immediate Mode?
Answer: Every frame, the entire UI is described anew; there is no widget tree persisting across frames.
Immediate Mode guides: if the code runs, the UI is depicted; remove the code, the UI is gone. No state, no hierarchy between frames.
⚠ Common mistake: Storing widgets as fields in the App struct to "build them once, reuse them later" — as in retained mode. egui has no persistent widget objects: anything not re-executed in
update()every frame simply does not exist. State belongs in your own fields (likename), not in buttons or labels.
Immediate mode in one sentence
Takeaways:
use eframe::egui;
struct MyApp {
name: String,
age: u32,
}
impl Default for MyApp {
fn default() -> Self {
Self {
name: "Rustacean User".to_owned(),
age: 28,
}
}
}
impl eframe::App for MyApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
// All UI code lives here, re-executed every frame
ui.heading("Hello egui!");
ui.horizontal(|ui| {
ui.label("Name:");
ui.text_edit_singleline(&mut self.name);
});
ui.add(egui::Slider::new(&mut self.age, 0..=120).text("Age"));
if ui.button("Greet").clicked() {
println!("Hello {}!", self.name);
}
});
}
}
fn main() {
let options = eframe::NativeOptions::default();
eframe::run_native(
"My egui App",
options,
Box::new(|_cc| Box::new(MyApp::default())),
);
}
// → console after clicking "Greet": Hello Rustacean User!
eframe::run_native starts the event loop — one frame per event or periodic
repaints.name, age) lives in your App type.update is called with &mut self — Rust guarantees: only one instance
processes state at a time → no data races without Arc<Mutex>.ui.…() returns a Response object that tells whether the user
interacted (.clicked(), .changed(), .hovered()).MyApp::default() — initial statectx.begin_frame() (implicit via CentralPanel::default().show(...))update() is called → Ephemeral UI for this frame:
allocations are dropped at the end of the frame automaticallyctx.end_frame() → rendering commands are executedTherefore: no need to store widgets in structs. The UI is code, your app is data.
Check: What is the role of implementing eframe::App?
Answer: Provide code that describes the UI for the current frame.
eframe::App has exactly one method: update(&mut self, ctx, frame). It is where you specify the current UI — every time.
⚠ Common mistake: Doing blocking work directly in
update()— astd::thread::sleep, a file read, or an HTTP call freezes the whole window, becauseupdate()runs on the UI thread and no frame is drawn until it returns. Move heavy work to background threads and send results back through a channel; then callctx.request_repaint().
The frame loop
Takeaways:
egui's layout strategy is "aligning and wrapping". Every widget reserves only as much space as it needs, no complex CSS grid.
egui::CentralPanel::default()
.show(ctx, |ui| { /* Main content */ });
egui::TopBottomPanel::top("top_bar").show(ctx, |ui| {
egui::menu::bar(ui, |ui| {
ui.menu_button("File", |ui| { /* … */ });
});
});
egui::SidePanel::left("side").show(ctx, |ui| {
ui.label("Sidebar");
});
Important: The order in code is the order of overlap:
SidePanel → TopBottomPanel → CentralPanel.
ui.horizontal(|ui| {
ui.label("First name:");
ui.text_edit_singleline(&mut first_name);
});
ui.vertical(|ui| {
ui.label("Error");
ui.label("Message…");
});
ui.separator(); // Horizontal line
ui.spacing_mut().slider_width = 200.0; // Global for this UI context
ui.with_layout(egui::Layout::right_to_left(egui::Align::TOP), |ui| {
ui.label("Right-aligned");
});
egui separates logic (app state) from appearance. Visuals can be switched globally:
// For the entire app (once per update):
ctx.set_visuals(egui::Visuals::dark());
// or
ctx.set_visuals(egui::Visuals::light());
// Per-widget:
ui.style_mut().text_styles.insert(
egui::TextStyle::Heading,
egui::FontId::new(24.0, egui::FontFamily::Proportional),
);
Check: Which layout method ensures widgets are placed side by side?
Answer: ui.horizontal(|ui| { ... })
ui.horizontal creates a horizontal layout context. All widgets created inside this closure will be placed left to right.
⚠ Common mistake: Calling
CentralPanelfirst and the panels afterwards — the central panel claims all remaining space, so laterSidePanel/TopBottomPanelcalls intrude on territory already handed out (egui warns about the order in debug builds). Always Side → Top first, then Central — and each panel id string may be used only once.
Layout without CSS
Takeaways:
Each widget that exposes user-edited values takes a &mut T reference:
ui.text_edit_singleline(&mut self.name);
ui.add(egui::Slider::new(&mut self.age, 0..=120));
if ui.checkbox(&mut self.active, "Active").changed() {
// self.active was modified
}
This means: A value cannot be edited in two widgets at the same time. This is not a bug, but a feature: it prevents data races and non-determinism.
egui identifies widgets by their Id. By default, the Id is derived from the widget type and the hierarchy in the UI tree.
If you, for example, dynamically render a list of items and each item should have its own text field, you must enforce unique ids:
for (id, item) in self.items.iter_mut().enumerate() {
ui.push_id(id, |ui| {
ui.text_edit_singleline(&mut item.name);
});
}
Without push_id, all text fields would share the same id and would edit a
shared value.
ui.dataSometimes only the UI needs its own state (e.g., a CollapsingHeader is open or
closed). For this, there's egui::Memory:
// Store UI-internal state at a specific id:
ui.data_mut(|d| d.insert_temp(id, true));
// Read it again in the next frame:
let was_open = ui.data(|d| *d.get_temp::<bool>(id).unwrap_or(false));
// → false as long as the id has not been written this frame
This is per-frame state — if a widget is not drawn in a frame, its state is discarded.
Check: What does ui.push_id do in a loop?
Answer: Each iteration widget receives a unique Id so egui does not mix up the state (e.g., in TextEdit or CollapsingHeader).
Without push_id, widgets created in a loop will share the same Id and thus their state will be merged (e.g., each TextEdit field will share the same text). push_id creates a new scoping block for ids.
⚠ Common mistake: Leaving out
ui.push_idinside loops — all created widgets inherit the same id and share one state: every text field types into the same content, all collapsing headers open and close in unison. Wrapping the widget block inui.push_id(index, |ui| …)gives each iteration its own identity.
UI code is ordinary Rust code
Rc<RefCell<…>> needed: Rust ownership replaces the hidden state management of retained-mode toolkits.Takeaways:
egui provides direct access to the Painter object for drawing custom graphics:
use egui::{Color32, Pos2, Stroke};
ui.painter().circle_filled(
Pos2::new(100.0, 100.0),
30.0,
Color32::from_rgb(100, 200, 100),
);
ui.painter().line_segment(
[Pos2::new(50.0, 50.0), Pos2::new(150.0, 150.0)],
Stroke::new(3.0, Color32::RED),
);
Color32 — 32-bit RGBA.Stroke defines lines: thickness + color + optional dashed lines.egui follows the "changed-driven" principle:
self.name = …) → next frame will repaint.ctx.request_repaint() forces a new frame even
without changes (useful for animations).Immediate mode costs CPU — but only for the widgets that are actually used.
Repeated request_repaint() without the app doing any processing → 60 fps loop,
CPU remains low (no GPU-sync issues).
eframe + wasm-bindgen → runs in browser via WebGL/WebGPU.egui-winit + custom renderer.For maximum performance on Desktop:
# Cargo.toml
[dependencies]
eframe = { version = "0.27", features = ["wgpu"] }
| Toolkit | Paradigm | Maturity | Typical Use-Cases | Pure Rust? |
|---|---|---|---|---|
| egui | Immediate Mode | ✅ | Tools, debug UIs, simple GUIs | ✅ |
| iced | Retained/Elm | ✅ | Desktop apps, complex UIs | ✅ (wgpu) |
| Slint | Retained/Yocto | ✅ | Embedded systems, QML-like | ❌ (C++/Rust) |
| Druid | Retained | ⚠️ | High-performance desktop apps | ✅ |
| Dioxus | Retained/VirtualDOM | ⚠️ | React-like applications | ✅ |
egui shines when you need quick, iterative and systems-level UIs — developer tools, debug overlays, prototypes. For classic desktop applications with complex navigation and state hierarchies, retained-mode toolkits are often the better fit.
Check: Which method forces egui to redraw every frame — even without state change?
Answer: ctx.request_repaint()
ctx.request_repaint() wakes up egui and triggers a new frame even if state has not changed — useful for animations or real-time updates.
⚠ Common mistake: Calling
ctx.request_repaint()unconditionally in everyupdate()— the app then asks for a new frame constantly and runs a 60-fps loop at full CPU even when there is nothing to do. Request a repaint only when work is actually pending (animation running, result arrived); for smooth continuous updatesrequest_repaint_after(Duration::from_millis(16))is the cheaper knob.
Control repaints deliberately
Takeaways:
Course navigation: ← Module 23 · All 27 modules · Module 25 →