1. An L-System Draws Plants Using String Rules
In Part 8, we applied the tree and Koch curve rules once and printed each result. Now we'll apply a rule for several generations and turn the resulting string into line segments. A Lindenmayer system (L-System) is a string-rewriting system created in 1968 by biologist Aristid Lindenmayer to model the growth of algae and plants.1
A starting string (the axiom) and a table of rules are enough to begin. In each generation the rules replace the characters of the previous string in parallel. To keep the example short enough to follow by hand, we'll start with F and use F -> F[+F][-F], a shorter rule than the tree preset in Part 8.
After generation 1 you get F[+F][-F]. In generation 2, the same rule replaces all three F characters already in the string in one pass.
To turn the resulting string into a drawing, we use Turtle Graphics. Picture a turtle holding a pen on a sheet of paper.
The turtle reads the string from left to right. When it reads F, it moves forward one step and draws a line. + turns it right and - turns it left.
The square brackets [ and ] let two branches start from the same spot. At [, record the turtle's position and which way it's facing. At ], take the most recent record and restore both values without drawing a line on the way back. The next branch can start from the same point on the trunk.
In this chapter, we combine collections (HashMap, Vec) and iterators (Iterator) with the struct, enum, and Result skills you already have to build a pure Rust L-System engine.
Keeping the calculation engine separate from the GUI lets you test the math automatically without opening a window.
In the final chapter (Part 10), our desktop GUI app will take the line segments produced by this engine and draw them straight onto the screen.23
2. Why Separate the Engine (src/lsystem.rs) from the UI (src/main.rs): UML Architecture
UML (Unified Modeling Language) gives us a notation for drawing program structure. This diagram puts the engine we will write here next to the GUI that will call it in Part 10.
The dashed box marks the lsystem module. LSystem expands the string, and build_segments reads it as drawing commands. Segment and LSystemError are data the engine returns without knowing about windows or clicks.
If string expansion and turtle math live inside the GUI button code, a simple bracket bug sends you back to the window to drag a slider and try it again.
Put the calculation in src/lsystem.rs and cargo test can exercise valid expansion and malformed brackets without opening a window.
The engine hands back coordinates in a Vec<Segment>. A terminal renderer, an SVG exporter, or a WebAssembly app can each use those coordinates without redoing the turtle math.
On failure the engine returns an LSystemError. The tests compare it with assert_eq!; the GUI in Part 10 displays the same error in red.
Split Code by What Changes, Not by Line Count
One file is fine at first. But if main takes input, rewrites the string, calculates turtle coordinates, and draws the window, you're editing unrelated jobs in the same place. Moving a slider ought to leave the string-rewriting code alone. After changing a rule, you want to test the calculation without launching a window.
There is no agreed number of lines for a clean function or file. Length is a cue to take a closer look; the single-responsibility principle tells you where to split. Keep work that changes together in one place and separate work that changes for different reasons. Here, main starts the program and calls the pieces in order. The lsystem module does the calculation. We still have one executable, so we still have one fn main().4
3. Creating a New Project and Writing src/lsystem.rs
If your terminal is still inside hello_rust, go up one level to the practice folder before creating the project for Parts 9 and 10. cargo new creates the directory, the Cargo.toml manifest, and the src/main.rs entry point.
cargo new lsystem-viewer
cd lsystem-viewerYour terminal is now in lsystem-viewer. This is the layout you'll have by the end of the section. Cargo already made Cargo.toml and src/main.rs, so the only new file you need to create in your editor is src/lsystem.rs.
lsystem-viewer/
βββ Cargo.toml
βββ src/
βββ main.rs
βββ lsystem.rsA collection is a data structure for managing several values together. Here we use two that can grow their heap storage as we add items.
The first is Vec<T> (a vector). Unlike a fixed-size array, a vector is a growable list that lets you push items onto the back and pop them off at runtime.
Here we use it both as a bookmark stack (Vec<Turtle>) and as the list of finished line segments (Vec<Segment>).
The second is HashMap<K, V>. It works like a dictionary that maps each key directly to its associated value.
In our engine, we use HashMap<char, String> to map a single character like 'F' to its replacement string like "F[+F][-F]".
Unlike Vec, HashMap is not imported automatically by default, so we add use std::collections::HashMap; at the very top of the file.
Now create a new file at src/lsystem.rs inside your project and type in the code below.
use std::collections::HashMap;
#[derive(Debug, PartialEq)]
pub enum LSystemError {
EmptyAxiom,
TooManyIterations { requested: u32, max: u32 },
UnmatchedPop,
UnclosedPush { remaining: usize },
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Segment {
pub x1: f32,
pub y1: f32,
pub x2: f32,
pub y2: f32,
}
#[derive(Debug, Clone, Copy)]
struct Turtle {
x: f32,
y: f32,
angle_deg: f32,
}
pub struct LSystem {
pub axiom: String,
pub rules: HashMap<char, String>,
}
impl LSystem {
pub fn new(axiom: &str, rule_pairs: &[(char, &str)]) -> Self {
let rules = rule_pairs
.iter()
.map(|(k, v)| (*k, (*v).to_string()))
.collect();
Self {
axiom: axiom.to_string(),
rules,
}
}
pub fn expand(&self, iterations: u32) -> Result<String, LSystemError> {
if self.axiom.trim().is_empty() {
return Err(LSystemError::EmptyAxiom);
}
if iterations > 10 {
return Err(LSystemError::TooManyIterations {
requested: iterations,
max: 10,
});
}
let mut current = self.axiom.clone();
for _ in 0..iterations {
let mut next = String::with_capacity(current.len() * 2);
for ch in current.chars() {
match self.rules.get(&ch) {
Some(replacement) => next.push_str(replacement),
None => next.push(ch),
}
}
current = next;
}
Ok(current)
}
}
pub fn build_segments(
commands: &str,
step_len: f32,
angle_deg: f32,
) -> Result<Vec<Segment>, LSystemError> {
let mut turtle = Turtle {
x: 0.0,
y: 0.0,
angle_deg: 90.0,
};
let mut stack: Vec<Turtle> = Vec::new();
let mut segments: Vec<Segment> = Vec::new();
for ch in commands.chars() {
match ch {
'F' | 'G' => {
let rad = turtle.angle_deg.to_radians();
let nx = turtle.x + step_len * rad.cos();
let ny = turtle.y + step_len * rad.sin();
segments.push(Segment {
x1: turtle.x,
y1: turtle.y,
x2: nx,
y2: ny,
});
turtle.x = nx;
turtle.y = ny;
}
'+' => turtle.angle_deg -= angle_deg,
'-' => turtle.angle_deg += angle_deg,
'[' => stack.push(turtle),
']' => {
turtle = stack.pop().ok_or(LSystemError::UnmatchedPop)?;
}
_ => {}
}
}
if !stack.is_empty() {
return Err(LSystemError::UnclosedPush { remaining: stack.len() });
}
Ok(segments)
}The file looks long at first, but it splits into four parts. Let's walk through it from top to bottom.
Visibility (pub) and Data Design
Visibility follows module boundaries. Structs, enums, functions, and struct fields are private by default, so we mark what src/main.rs needs to use from this module as pub.
That is why LSystemError, Segment, LSystem, and the main functions are marked pub. Turtle, on the other hand, is only an internal helper for tracking coordinates inside build_segments, so we omit pub to keep it private.
A common beginner pitfall is marking a struct pub while forgetting to mark its fields (like x1 and y1) pub as well.
If the fields stay private, reading seg.x1 from another file triggers a compiler error, so every field meant to be read externally needs pub too.
The Iterator Chain and Closure in LSystem::new
LSystem::new accepts its rules as a slice of pairs, &[(char, &str)]. This saves callers from creating a HashMap::new() and calling insert over and over.
Instead, the constructor builds the HashMap in one expression using .iter().map(|(k, v)| (*k, (*v).to_string())).collect().
.iter() creates an iterator that yields each element from the slice one by one. Because it borrows elements instead of taking ownership, each item reaches the next step as a reference of type &(char, &str).
Next, .map(...) transforms each yielded item into a new value. The expression |(k, v)| (*k, (*v).to_string()) inside the parentheses is a closure. Think of a closure as an anonymous inline function where parameters sit between vertical bars |...| and the return expression follows on the right.
The asterisk (*) in *k and *v is the dereference operator. It takes off one layer of reference to reach the underlying value. Because .iter() yields references to tuples, k has type &char and v has type &&str. Using *k copies out the char value, and (*v).to_string() unwraps the &str and converts it into an owned String.
Finally, .collect() gathers the transformed (char, String) pairs into a collection. Even though we did not write the target type next to collect(), the compiler sees that rules is stored in Self { axiom, rules } with type HashMap<char, String> and infers it automatically.
The expand Function: Safety Guards and Pre-Allocating Memory
Before doing any work, expand uses two guard clauses to reject invalid inputs.
Checking self.axiom.trim().is_empty() catches blank or whitespace-only axioms and returns EmptyAxiom, while iterations > 10 caps the depth at 10 and returns TooManyIterations.
This example caps the generation count at 10 because rules that multiply the branches can make the string grow exponentially.
If a single F expands into a string containing five Fs, then after just 10 generations there are already 5^10 (over 9.76 million) Fs. Without an upper bound, passing 20 would exhaust memory in an instant and freeze the program.
Inside the expansion loop, we create the next generation's string with String::with_capacity(current.len() * 2).
An empty String::new() buffer needs to grow as we append text. Reserving twice the current byte length gives the next generation a head start and can save some reallocations.
The inner loop walks through each character using current.chars() and looks it up in the rule table with self.rules.get(&ch).
If a rule exists (Some(replacement)), it appends the whole replacement string with push_str; if not (None), as with +, -, [, and ], it keeps the original character with push.
The build_segments Function: Turtle Stack Tracing and Bracket Errors
build_segments reads the expanded command string and turns it into a list of line-segment coordinates. The turtle starts at the origin (0.0, 0.0) facing straight up (90.0 degrees).
On F or G, it converts the heading to radians with to_radians(), computes the next point (nx, ny) using cos and sin, pushes a Segment onto the vector, and moves the turtle forward.
Follow the turtle as it reads the short command string "F[+F][-F]" one character at a time.
1. First F: the turtle walks one step upward from the origin and draws the trunk (segment 1).
2. [: it saves the trunk tip's position and angle with stack.push(turtle). Because Turtle derives Copy, pushing it onto the stack stores a snapshot copy without moving ownership away from the turtle variable.
3. + and F: the turtle turns right and draws the right branch (segment 2).
4. ]: stack.pop() retrieves the saved trunk-tip state and writes it back into turtle. The turtle jumps straight back from the tip of the branch to the top of the trunk.
5. [, -, F, ]: the turtle bookmarks the trunk tip again, turns left, draws the left branch (segment 3), and returns on the final ]. Once every character has been processed, we have 3 segments and an empty stack.
What happens if someone writes mismatched brackets? Consider "F]F", where a closing ] appears without a matching [.
Calling stack.pop() on an empty stack returns None, so chaining .ok_or(LSystemError::UnmatchedPop)? converts None into Err(LSystemError::UnmatchedPop) and returns early through the ? operator.
In the opposite case, such as "F[+F[", the string ends with opening brackets still unclosed, which triggers if !stack.is_empty() after the loop.
We count how many saved turtle states remain with stack.len() and report the exact number in UnclosedPush { remaining }.
4. Verifying Happy Paths and Error Paths with cargo test
Rust and Cargo include built-in unit testing out of the box, with no external test framework required. Append the test module below to the bottom of src/lsystem.rs.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expands_fractal_tree_one_step() {
let sys = LSystem::new("F", &[('F', "F[+F]F[-F]F")]);
let expanded = sys.expand(1).expect("single-step expansion should succeed");
assert_eq!(expanded, "F[+F]F[-F]F");
}
#[test]
fn rejects_empty_axiom_and_too_many_iterations() {
let empty = LSystem::new(" ", &[]);
assert_eq!(empty.expand(1), Err(LSystemError::EmptyAxiom));
let tree = LSystem::new("F", &[('F', "FF")]);
assert_eq!(
tree.expand(11),
Err(LSystemError::TooManyIterations {
requested: 11,
max: 10
})
);
}
#[test]
fn detects_unmatched_closing_bracket() {
let err = build_segments("F]F", 10.0, 25.0);
assert_eq!(err, Err(LSystemError::UnmatchedPop));
}
#[test]
fn detects_unclosed_opening_brackets() {
assert_eq!(
build_segments("F[+F[", 10.0, 25.0),
Err(LSystemError::UnclosedPush { remaining: 2 })
);
}
#[test]
fn builds_expected_segment_count() {
let segs = build_segments("F[+F][-F]", 10.0, 25.0).expect("valid commands should parse");
assert_eq!(segs.len(), 3);
}
}This test block introduces a few new pieces of syntax. Learning what each one does will help you read tests in any Rust codebase.
#[cfg(test)] includes this module when Rust compiles the test target. cargo test turns it on for that build; the ordinary executable leaves the tests out.
Directly below it, mod tests groups the test functions inside a child module.5
use super::*; brings everything from the parent module (src/lsystem.rs) into the test module at once. A child module in the same file can even access private items that lack pub, which makes it easy to test internal details thoroughly.
The #[test] attribute above each function tells Cargo to run it as an automated test case.
The assert_eq!(left, right) macro checks that two values are equal. If they differ, the test fails and prints both the expected and actual values side by side.
This is why we added #[derive(Debug, PartialEq)] to LSystemError earlier. PartialEq lets assert_eq! compare two error values with ==, and Debug lets it format and display them if a test fails.
Notice that our test suite checks both happy paths (single-step expansion and generating 3 segments) and error paths (empty axiom, 11 iterations, unmatched closing bracket, and unclosed opening brackets).
If you only test happy paths, accidentally deleting a guard clause during a later edit could slip by unnoticed. Locking in the exact errors for invalid inputs gives us confidence to plug this engine into the Part 10 GUI.
Now add mod lsystem; at the top of src/main.rs so the Rust compiler includes src/lsystem.rs in the crate. Then run cargo test in your terminal.
Cargo doesn't gather every .rs file under src into the executable. The compiler reads src/lsystem.rs as this module when it sees mod lsystem;. A use statement brings names from a module that's already there into scope; it can't take the place of mod. If you only create the file, its tests won't be discovered either.6
Here's what the file looks like after adding that one line above the existing fn main(). The executable has the same entry point; we've just connected the file that owns the calculation.
mod lsystem;
fn main() {
println!("Hello, world!");
}cargo testOutput:
running 5 tests
test lsystem::tests::builds_expected_segment_count ... ok
test lsystem::tests::detects_unclosed_opening_brackets ... ok
test lsystem::tests::detects_unmatched_closing_bracket ... ok
test lsystem::tests::expands_fractal_tree_one_step ... ok
test lsystem::tests::rejects_empty_axiom_and_too_many_iterations ... ok
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered outAll 5 tests passed with ok. Normal expansion and segment generation work as expected, and every error case from empty axioms to mismatched brackets is verified.
In the final chapter (Part 10), we will render the Vec<Segment> produced by this engine inside a real desktop GUI window and watch our fractal tree grow.
Footnotes
- Aristid Lindenmayer, "Mathematical models for cellular interactions in development", Journal of Theoretical Biology (1968). β©
- The Rust Programming Language, Ch. 8.3 Storing Keys with Associated Values in Hash Maps: https://doc.rust-lang.org/book/ch08-03-hash-maps.html β©
- The Rust Programming Language, Ch. 13.2 Processing a Series of Items with Iterators: https://doc.rust-lang.org/book/ch13-02-iterators.html β©
- The Rust Programming Language, Refactoring to Improve Modularity and Error Handling. https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#separating-concerns-in-binary-projects β©
- The Rust Programming Language, Ch. 11.1 How to Write Tests: https://doc.rust-lang.org/book/ch11-01-writing-tests.html β©
- The Rust Programming Language, Separating Modules into Different Files. https://doc.rust-lang.org/book/ch07-05-separating-modules-into-different-files.html β©