1. Why Choose eframe and egui for Your First Rust GUI
An L-System is far too visual to leave as raw coordinates printed in a terminal. A standalone desktop window with buttons and sliders, like the everyday programs you use on your computer, is called a GUI (Graphical User Interface).
The Rust ecosystem offers several GUI toolkits, including Iced, Slint, Tauri, and egui.
For beginners who want to open a window on Windows, macOS, and Linux with minimal setup, eframe (the official app framework for egui) is one of the easiest places to start.1
egui uses an approach called Immediate-mode GUI.
In an immediate-mode GUI, the code describes the widgets from the app's current data each time it repaints. That keeps the value you see in the controls close to the variable you change in code. Input and window resizing are two reasons the framework calls update() again.
Re-running L-System string expansion and segment math on every single frame would waste CPU cycles.
Instead, we cache the computed segments inside our app struct (self.segments) and call self.recompute() only when the user actually changes a preset or moves a slider.
The app itself is written in pure Rust. If you are on Linux, make sure you install the graphics development packages listed in the eframe 0.31.1 setup guide first.
The app follows the pattern from Part 8. We implement the eframe::App trait for our app struct, and the framework calls our update method when it needs to repaint the window.2
2. Why Is a GUI Structured This Way: UML, Buttons, and Sliders
In the earlier terminal examples, we print the result and the program exits. This app keeps running until you close the window. A click, a slider drag, or a resize can give it a reason to repaint.
Qt and Java Swing are examples of retained-mode toolkits. They keep widgets around as objects; you create the button and attach a callback to run when it is clicked. If both the widget and the app store a value, you have to keep the two in sync.
With egui, update() reads the current values from LSystemApp and describes the widgets for that frame. An if next to the radio button can check whether it changed the selected value.
The widgets box on the right is a list of controls, not a picture of their positions in the window. egui::SidePanel::left("controls") puts the settings panel on the left, and one call to ui.radio_value(...) per preset gives us three radio buttons that share one selection.
Below the presets, egui::Slider::new(...) supplies the controls for iteration count and turn angle. egui::CentralPanel::default() fills the remaining space, where painter.line_segment(...) draws the fractal.
This is why LSystemApp keeps segments: Vec<Segment>. After a resize, update() has to fit the drawing to the new canvas, but the coordinates are still the same. There is no need to expand the string or rerun cos and sin for each segment.
We compute the first set of segments at startup. After that, the panel calls self.recompute() when a preset or slider value changes (changed == true). A resize alone just redraws the cached segments at a new scale.
3. Adding eframe to Cargo.toml
Open Cargo.toml in the lsystem-viewer project from Part 9 and add eframe under [dependencies]. Cargo.toml is the blueprint file that tells Cargo which external libraries (called crates in Rust) your project depends on.
Because egui ships with a built-in default font that covers English and common symbols, you do not need to download any extra font files to run this app.
Later in this lesson, we will also see how to bundle a custom font when you want to display non-Latin scripts like Korean, Japanese, or Chinese.
[package]
name = "lsystem-viewer"
version = "0.1.0"
edition = "2024"
[dependencies]
eframe = "0.31"The first time you build after adding an external crate, Cargo downloads its dependencies from crates.io and compiles them, which can take one to two minutes.
Subsequent builds reuse those compiled dependencies and only recompile your own changed files, finishing in just a few seconds.
4. src/main.rs: Presets and Real-Time Sliders in Action
Replace src/main.rs with the code below. It looks long at first, so read it in four parts: preset definitions, app state and recomputation, per-frame rendering, and the main() entry point.
The left panel holds our presets (Fractal Tree, Koch Curve, Dragon Curve) plus sliders for iterations and turn angle, while the central canvas auto-fits the segments from Part 9's lsystem::build_segments to the window.
mod lsystem;
use eframe::egui;
use lsystem::{LSystem, Segment, build_segments};
#[derive(Debug, Clone, Copy, PartialEq)]
enum Preset {
FractalTree,
KochCurve,
DragonCurve,
}
impl Preset {
fn label(self) -> &'static str {
match self {
Preset::FractalTree => "Fractal Tree",
Preset::KochCurve => "Koch Curve",
Preset::DragonCurve => "Dragon Curve",
}
}
fn default_params(self) -> (u32, f32) {
match self {
Preset::FractalTree => (4, 25.0),
Preset::KochCurve => (3, 90.0),
Preset::DragonCurve => (9, 90.0),
}
}
fn build_system(self) -> LSystem {
match self {
Preset::FractalTree => LSystem::new("F", &[('F', "F[+F]F[-F]F")]),
Preset::KochCurve => LSystem::new("F", &[('F', "F+F-F-F+F")]),
Preset::DragonCurve => LSystem::new("FX", &[('X', "X+YF+"), ('Y', "-FX-Y")]),
}
}
}
struct LSystemApp {
preset: Preset,
iterations: u32,
angle_deg: f32,
segments: Vec<Segment>,
error_msg: Option<String>,
}
impl LSystemApp {
fn new() -> Self {
let preset = Preset::FractalTree;
let (iterations, angle_deg) = preset.default_params();
let mut app = Self {
preset,
iterations,
angle_deg,
segments: Vec::new(),
error_msg: None,
};
app.recompute();
app
}
fn recompute(&mut self) {
let system = self.preset.build_system();
let result = system
.expand(self.iterations)
.and_then(|cmd| build_segments(&cmd, 10.0, self.angle_deg));
match result {
Ok(segs) => {
self.segments = segs;
self.error_msg = None;
}
Err(err) => {
self.segments.clear();
self.error_msg = Some(format!("Generation failed: {:?}", err));
}
}
}
}
impl eframe::App for LSystemApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::SidePanel::left("controls")
.resizable(false)
.min_width(220.0)
.show(ctx, |ui| {
ui.heading("L-System Settings");
ui.separator();
let mut changed = false;
for candidate in [Preset::FractalTree, Preset::KochCurve, Preset::DragonCurve] {
if ui
.radio_value(&mut self.preset, candidate, candidate.label())
.changed()
{
let (iters, angle) = candidate.default_params();
self.iterations = iters;
self.angle_deg = angle;
changed = true;
}
}
ui.add_space(12.0);
let max_iter = match self.preset {
Preset::DragonCurve => 10,
_ => 5,
};
if ui
.add(egui::Slider::new(&mut self.iterations, 1..=max_iter).text("Iterations"))
.changed()
{
changed = true;
}
if ui
.add(egui::Slider::new(&mut self.angle_deg, 5.0..=120.0).text("Turn Angle"))
.changed()
{
changed = true;
}
if changed {
self.recompute();
}
ui.add_space(12.0);
ui.label(format!("Segments drawn: {}", self.segments.len()));
if let Some(msg) = &self.error_msg {
ui.colored_label(egui::Color32::RED, msg);
}
});
egui::CentralPanel::default().show(ctx, |ui| {
let rect = ui.available_rect_before_wrap();
ui.allocate_rect(rect, egui::Sense::hover());
let painter = ui.painter_at(rect);
painter.rect_filled(rect, 0.0, egui::Color32::from_rgb(255, 253, 248));
if self.segments.is_empty() {
return;
}
let mut min_x = f32::INFINITY;
let mut max_x = f32::NEG_INFINITY;
let mut min_y = f32::INFINITY;
let mut max_y = f32::NEG_INFINITY;
for s in &self.segments {
min_x = min_x.min(s.x1).min(s.x2);
max_x = max_x.max(s.x1).max(s.x2);
min_y = min_y.min(s.y1).min(s.y2);
max_y = max_y.max(s.y1).max(s.y2);
}
let pad = 28.0;
let span_x = (max_x - min_x).max(1.0);
let span_y = (max_y - min_y).max(1.0);
let scale = ((rect.width() - pad * 2.0) / span_x)
.min((rect.height() - pad * 2.0) / span_y);
if scale <= 0.0 {
return;
}
let offset_x = rect.center().x - ((min_x + max_x) * 0.5) * scale;
let offset_y = rect.center().y + ((min_y + max_y) * 0.5) * scale;
let stroke = egui::Stroke::new(1.4_f32, egui::Color32::from_rgb(43, 138, 62));
for s in &self.segments {
let p1 = egui::pos2(offset_x + s.x1 * scale, offset_y - s.y1 * scale);
let p2 = egui::pos2(offset_x + s.x2 * scale, offset_y - s.y2 * scale);
painter.line_segment([p1, p2], stroke);
}
});
}
}
fn main() -> eframe::Result<()> {
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default().with_inner_size([960.0, 680.0]),
..Default::default()
};
eframe::run_native(
"Rust L-System Viewer",
options,
Box::new(|_cc| Ok(Box::new(LSystemApp::new()))),
)
}Every concept from the first nine parts shows up somewhere in this file. Let us walk through each section and see why it is written this way.
Presets and App State: enum, struct, and Segment Caching
At the top, mod lsystem; pulls in the src/lsystem.rs module we built in Part 9. Below it, Preset is an enum representing our three fractal shapes, and #[derive(Debug, Clone, Copy, PartialEq)] asks the compiler to generate four standard traits automatically.
Copy and PartialEq do real work here. Copy lets us pass a Preset value into methods without moving ownership, while PartialEq enables == comparisons, which egui's radio_value widget needs in order to tell which preset is currently selected.
In label(self) -> &'static str, the 'static lifetime means a string slice that lives for the entire duration of the program. String literals like "Fractal Tree" are baked directly into the executable, so we can return a reference to them without allocating a new String on the heap.
LSystemApp is a plain data struct holding all of our app's state: the selected preset, iterations, turn angle, cached segments: Vec<Segment>, and error_msg: Option<String>.
Inside recompute(&mut self), Result::and_then chains string expansion (expand) and segment generation (build_segments) together.
If everything succeeds, we replace self.segments; if an error occurs, we display a red error label in the sidebar instead of crashing the app.
Drawing via a Trait: impl eframe::App and the .changed() Trap
In Part 8, we described a trait as a contract promising that a type implements specific methods.
The impl eframe::App for LSystemApp block fulfills that contract. When the window needs repainting, eframe calls update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame). The underscore in _frame tells the compiler we intentionally leave that parameter unused.
In egui::SidePanel::left("controls")...show(ctx, |ui| { ... }), the |ui| { ... } part is a closure, an anonymous inline function. eframe prepares the left panel region and hands our closure a ui handle so we can add widgets inside it.
The radio buttons use .changed() instead of .clicked() for a reason. If we used .clicked(), accidentally clicking the already-selected "Fractal Tree" button a second time would still trigger the if block and reset the angle and iteration sliders you just adjusted back to their defaults (4 and 25.0). By contrast, .changed() returns true only when self.preset actually switches to a different variant.
The sliders also set changed = true only when their value moves within the inclusive range (such as 1..=max_iter), and if changed { self.recompute(); } at the end avoids pointless recalculation. Dragon Curve grows more gently per step so we allow up to 10 iterations, whereas Fractal Tree and Koch Curve explode quickly and are capped at 5.
At the bottom of the panel, if let Some(msg) = &self.error_msg is a concise pattern match that runs only when an error message exists. Borrowing with & keeps ownership inside self.error_msg so it remains available on the next frame.
Bounding Box and Auto-Fit Math
Inside CentralPanel, we grab the remaining canvas rectangle with available_rect_before_wrap(), get a drawing brush with painter_at(rect), and fill it with a warm cream background.
Next, we scan every endpoint in self.segments to find the leftmost (min_x), rightmost (max_x), lowest (min_y), and highest (max_y) coordinates. Initializing those variables to f32::INFINITY and f32::NEG_INFINITY guarantees that the very first real coordinate updates them. After one pass over the segments, we have an exact bounding box around the entire shape.
Now fit the bounding box by computing a scale factor. Calling .max(1.0) on span_x and span_y prevents division by zero if all segments lie on a single straight line. Picking the smaller (.min) of the horizontal and vertical scale factors keeps the fractal proportional without stretching or clipping outside the panel.
The guard right below it, if scale <= 0.0 { return; }, handles a canvas that is too small to draw in. If either side of the canvas is no larger than the two margins (56 points in total), the scale becomes zero or negative. The guard skips drawing in that case. Without this early return, multiplying by a negative scale would flip the drawing upside down and backwards in the wrong place.
Notice the minus sign on y in the call to egui::pos2. In the engine's coordinates y increases upward; in egui's drawing coordinates it increases downward. Subtracting s.y1 * scale from offset_y flips the vertical axis so our Fractal Tree grows upward instead of hanging upside down.
For the same reason, offset_y adds ((min_y + max_y) * 0.5) * scale to rect.center().y. Plugging the shape's vertical midpoint y = (min_y + max_y) * 0.5 into offset_y - y * scale cancels both terms, placing the fractal's center at rect.center().y.
In 1.4_f32, the suffix names the width type passed to egui::Stroke::new(1.4_f32, ...). Its width argument must convert into f32. On Rust 1.98.1 a bare 1.4 falls back to f32 because the default f64 cannot be converted that way, and the compiler warns about it.
Adding the _f32 type suffix removes any ambiguity.
App Entry Point and Custom Fonts: Box::new and include_bytes!
Finally, let us look at main(). When creating NativeOptions, we set only the initial window size to 960x680 and fill in all remaining fields using ..Default::default().
The third argument to eframe::run_native is Box::new(|_cc| Ok(Box::new(LSystemApp::new()))).
Part 8 used a trait to work with several concrete types. Here eframe takes ownership of both the initializer and the concrete app through boxed values, so it can use each through its common interface.
The outer Box::new heap-allocates the startup closure, and the inner Ok(Box::new(LSystemApp::new())) hands our eframe::App implementation over to eframe.
The closure's parameter cc (CreationContext) is passed right after the window is created and before the first frame is drawn.
Right now our English labels work out of the box with egui's built-in font, so we ignore _cc.
If you ever want to render non-Latin scripts such as Korean, Japanese, or Chinese without seeing missing-glyph boxes, you can load a .ttf or .otf file at compile time with the include_bytes! macro inside that startup closure.3
Using include_bytes! embeds the font's raw bytes directly inside your compiled binary so you never have to ship a separate assets folder.
Wrapping that egui::FontData in std::sync::Arc::new and registering it on egui::FontDefinitions via cc.egui_ctx.set_fonts(fonts) lets egui share the multi-megabyte font data safely without duplicating it in memory.
5. Running the App and Playing with the Sliders
By default, cargo run compiles in debug mode with optimizations turned off for faster builds. When drawing thousands of fractal segments in real time, a release build with compiler optimizations enabled feels much smoother.
Run the app with --release from your terminal.
cargo run --releaseOutput:
Compiling lsystem-viewer v0.1.0
Finished `release` profile [optimized] target(s) in 3.42s
Running `target/release/lsystem-viewer`
The window starts at 960Γ680 logical points. Drag the Turn Angle slider on the left and the green Fractal Tree opens or closes its branches.
Resize the window and the app recalculates the fit from the available canvas, keeping the fractal centered when there is room to draw.
Try switching to Koch Curve or Dragon Curve and tweaking the iterations and turn angle. The Koch Curve preset here is the Quadratic Koch Curve, which turns 90 degrees and replaces one segment with five.
Moving the angle slider slowly shows how changing a single number turns the exact same rewriting rule into completely new geometric patterns.
Keep the Window and Add a Terminal Entry Point
Once the GUI above runs, try checking the segment count in a terminal without opening a window. The two interfaces need to start independently, so give them separate executables. There's no need for a second project. In lsystem-viewer, Cargo builds the default executable and src/bin/lsystem-cli.rs as separate targets. Two main functions don't run one after the other in the same program. Each executable gets one of its own.4
lsystem-viewer/
βββ Cargo.toml
βββ src/
βββ lib.rs
βββ lsystem.rs
βββ main.rs
βββ gui.rs
βββ bin/
βββ lsystem-cli.rsCreate src/lib.rs with the single line below. lib.rs is the root file of the shared library. Keep the expansion and coordinate calculations in src/lsystem.rs from Part 9. Declare the module with pub mod so that both executables can call the same code.
pub mod lsystem;Copy the entire GUI from Section 4 into a new src/gui.rs file. At the top of that file, replace everything from mod lsystem; through the two use lines with these two imports. The package name lsystem-viewer uses a hyphen; in Rust code, the library name lsystem_viewer uses an underscore.
use eframe::egui;
use lsystem_viewer::lsystem::{LSystem, Segment, build_segments};At the bottom of the copied file, change fn main() -> eframe::Result<()> to pub(crate) fn run() -> eframe::Result<()>. Keep its body as it is. pub(crate) lets the binary's main call it.
Now replace all of the old src/main.rs with the code below. Its job is to link the GUI module and call gui::run() when the executable starts.
mod gui;
fn main() -> eframe::Result<()> {
gui::run()
}Finally, create src/bin/ and put the code below in src/bin/lsystem-cli.rs. As in Part 7, ? returns early on an engine error. Here main returns Err and the program reports the error in the terminal. On success it prints just the number of segments drawn by F[+F][-F].
use lsystem_viewer::lsystem::{LSystem, LSystemError, build_segments};
fn main() -> Result<(), LSystemError> {
let system = LSystem::new("F", &[('F', "F[+F][-F]")]);
let commands = system.expand(1)?;
let segments = build_segments(&commands, 10.0, 25.0)?;
println!("{}", segments.len());
Ok(())
}Run these commands from lsystem-viewer, where Cargo.toml lives. The tests exercise the shared engine. The first executable prints 3; the second opens the same GUI as before. With two binaries and no default selected, plain cargo run can't choose between them. Use --bin to name the one you want.5
cargo test --lib
cargo run --bin lsystem-cli
cargo run --release --bin lsystem-viewerWhen Each Piece Grows, Split Along Its Responsibilities
Later the rewrite rules might get more involved, the GUI might gain editing tools, and the CLI might start taking arguments. Here's where those pieces could go. There's no point creating empty files now. Move the work when you have a reason to change or test it on its own.
lsystem-viewer/
βββ Cargo.toml
βββ src/
β βββ lib.rs
β βββ lsystem.rs
β βββ lsystem/
β β βββ rewrite.rs
β β βββ turtle.rs
β βββ main.rs
β βββ gui.rs
β βββ gui/
β β βββ controls.rs
β β βββ canvas.rs
β βββ bin/
β βββ lsystem-cli/
β βββ main.rs
β βββ args.rs
βββ tests/
βββ engine.rsPut rewriting and the iteration limit in lsystem/rewrite.rs, and turns and segment calculation in lsystem/turtle.rs. Declare mod rewrite; and mod turtle; in lsystem.rs. Use pub use rewrite::LSystem; and pub use turtle::{Segment, build_segments}; to keep the same public names available. Since both rewrite.rs and turtle.rs return LSystemError, keep LSystemError in lsystem.rs or re-export it with pub use as well. The CLI and GUI can keep using the same paths when the rewriting implementation changes.
Let gui/controls.rs read buttons and sliders and gui/canvas.rs decide where to draw the supplied coordinates. Declare both as submodules in gui.rs. If the CLI grows options such as --steps, move src/bin/lsystem-cli.rs to src/bin/lsystem-cli/main.rs and declare its neighboring args.rs with mod args;. Don't leave the old single-file target in place. The binary is still named lsystem-cli.
The tree has more files, but it still has just two program entry points. An integration test in tests/engine.rs can exercise the engine's public API without setting up a button or parsing an argument. A better test of the structure than fitting it on one screen is whether moving a button leaves the engine files alone.
6. Wrapping Up Part 10: Ready to Read Rust Docs on Your Own
We started Part 1 by asking how ML-style type ideas fit inside C-like syntax.
Along the way, you ran your first program, learned expression-based syntax, tackled ownership and borrowing, modeled data with struct, enum, and match, handled failure explicitly with Option, Result, and ?, understood why Rust favors traits over class inheritance, and finished by shipping a real desktop GUI app.
Rust has a steeper learning curve at the start, but once ownership, traits, and Result click into place, the compiler becomes the most reliable code reviewer you could ask for.
Official documentation and crate examples should feel far less intimidating from here on.
If you want to push this L-System viewer further, try extending it yourself. You could add a branch depth field to Segment to color trunks brown and tips bright green, or add a button that saves the current canvas as a PNG image.
Footnotes
- Official egui / eframe repository and documentation: https://github.com/emilk/egui β©
- docs.rs, eframe::App trait API documentation: https://docs.rs/eframe/0.31.1/eframe/trait.App.html β©
- Rust Standard Library, std::includebytes! macro documentation: [https://doc.rust-lang.org/std/macro.includebytes.html](https://doc.rust-lang.org/std/macro.include_bytes.html) β©
- The Cargo Book, Cargo Targets. https://doc.rust-lang.org/cargo/reference/cargo-targets.html β©
- The Cargo Book, cargo run: Target Selection. https://doc.rust-lang.org/cargo/commands/cargo-run.html#target-selection β©