Skip to content
RustLearn

Module 20 — Idioms, Performance & Capstones

Goal

Idiomatic API design, the anti-patterns to unlearn, profiling and optimization — then four full capstone projects to build from scratch.

Start here — what this module is really about

You know the language now. This module is about writing it the way experienced Rust developers write it, and then proving it on four real projects.

Three themes run through the sections:

API design is about the caller, not the implementation. A handful of conventions do most of the work: take &str rather than String in parameters so every caller can pass what they have; accept impl IntoIterator rather than demanding a Vec; return Result rather than panicking in a library; implement the standard traits so your type works with everyone else's code. Each one is small; together they are the difference between a crate people enjoy and one they tolerate.

Some habits are worth unlearning deliberately. Reaching for .clone() when a borrow would do. unwrap() in a library. Rc<RefCell<T>> used to sidestep a design problem rather than to solve a genuine sharing one. Stringly-typed data where an enum belongs. All of these compile, and all of them are the compiler telling you something you did not want to hear.

Optimise by measurement, never by instinct. Rust is fast by default, which makes it especially tempting to write unpleasant code chasing speed you never needed. Profile first. In practice the answer is almost always an allocation in a hot loop or a clone that borrowing removes — not the clever restructuring you were about to attempt.

Then the capstones. Four projects — a search tool, a persistent task manager, a threaded web server, an async crawler — each exercising a different span of the course. They are where the modules stop being separate topics and become one skill.

The one sentence to remember: design for the caller, unlearn the habits that were workarounds, and measure before you optimise.

Learning objectives

  • Write APIs that feel native to Rust
  • Recognize and avoid common anti-patterns
  • Profile before optimizing; know the standard optimizations
  • Complete four capstone projects that exercise the whole course

20.1 API design idioms

Accept the widest input, return the most specific output

rust
// ❌
fn process(data: &Vec<String>, name: &String) -> Vec<String>

// ✅
fn process(data: &[String], name: &str) -> Vec<String>

// ✅ even more flexible for constructors
fn new(name: impl Into<String>) -> Self
fn open(path: impl AsRef<Path>) -> io::Result<File>

Naming conventions

PrefixReceiverCostExample
as_&selffreeas_str, as_bytes
to_&selfallocatesto_string, to_owned
into_selfconsumesinto_iter, into_bytes

get_ is not used — write fn name(&self) -> &str, not get_name.

Make illegal states unrepresentable

rust
// ❌
struct Connection { url: String, connected: bool, socket: Option<Socket> }

// ✅
enum Connection { Disconnected { url: String }, Connected { socket: Socket } }

Parse, don't validate

rust
// ❌ validation can be forgotten downstream
fn is_valid_email(s: &str) -> bool

// ✅ the type carries the proof
struct Email(String);
impl Email { fn parse(s: &str) -> Result<Email, EmailError> { ... } }

Implement the standard traits

Derive Debug on everything. Consider Default, Clone, PartialEq. Implement Display for user-facing types, From for conversions, FromStr for parseable types, IntoIterator for collections. Users expect them.

Use the type system for units and IDs

rust
struct UserId(u64);
struct OrderId(u64);
fn get_user(id: UserId) -> User      // can't accidentally pass an OrderId

Builders for many optional fields; enums for mutually exclusive ones

Covered in modules 06 and 07.

The API conventions that matter most

Five decisions, each appearing in nearly every crate you will write:

rust
// 1. Accept borrowed, return owned.
fn normalise(input: &str) -> String { }     // ✅ any caller can pass anything
fn normalise(input: String) -> String { }   // ✗ forces the caller to give it up

// 2. Be generic over what you iterate.
fn total(items: impl IntoIterator<Item = u32>) -> u32 { }   // ✅ Vec, array, iterator
fn total(items: Vec<u32>) -> u32 { }                        // ✗ Vec or nothing

// 3. Return Result from libraries. Let the caller decide what is fatal.
fn parse(s: &str) -> Result<Config, ParseError> { }
fn parse(s: &str) -> Config { panic!() }                    // ✗ not your call

// 4. Implement the standard traits so your type fits the ecosystem.
#[derive(Debug, Clone, PartialEq)]
pub struct Config { }

// 5. Make invalid states unrepresentable — module 07, applied to your API.
pub enum Connection { Disconnected, Connected { id: String } }

The unifying question, worth asking of every public function you write: what is the least I can demand of the caller, and the most I can promise them? Take the most permissive input type that does the job; return the most useful thing you can; and let the type system carry the rules so the documentation does not have to.

Analogy — design the door, not the room

A well-designed API is judged the way a building's entrance is: not by how clever the plumbing is, but by whether a stranger can walk in and do the obvious thing without being told. Take &str, return owned values, accept impl IntoIterator, name things after what they mean to the caller — every one of these idioms is about the door, not the room.

20.2 Anti-patterns

Anti-patternBetter
.clone() scattered to appease the borrow checkerrestructure ownership, or borrow
.unwrap() in library codereturn Result, or expect with a real reason
Rc<RefCell<T>> as the defaultprefer ownership, indices, or message passing
String parameters everywhere&str
-> Box<dyn Error> in a public library APIa concrete error enum (thiserror)
Deeply nested match?, let else, early returns, combinators
Stringly-typed data (&str for enums)real enums
impl Trait sprinkled to avoid naming typesname the type when it's public API
Premature genericsone concrete type until you have a second caller
Fighting the compiler for an hourstep back; the design is probably wrong

20.3 Performance

Measure first

bash
cargo build --release                     # never profile debug builds
cargo bench                               # criterion
cargo install flamegraph && cargo flamegraph
perf stat ./target/release/myapp

The first rule is that your intuition about where the time goes is wrong. Profile.

Then apply the standard wins

Allocation is usually the top cost:

rust
let mut v = Vec::with_capacity(n);        // avoid repeated reallocation
let mut s = String::with_capacity(n);
buf.clear();                              // reuse a buffer instead of reallocating

Avoid needless copies:

rust
for item in &collection { }               // not `collection.clone()`
fn f(s: &str)                             // not `fn f(s: String)`
Cow<'_, str>                              // borrow until you must own

Choose the right data structure:

  • Vec beats LinkedList almost always (cache locality)
  • HashMap for lookup, Vec for iteration, BTreeMap for ordered
  • Small collections: a Vec linear scan beats a HashMap below ~20 elements
  • rustc-hash/ahash for non-adversarial hashing

Enable optimizations:

toml
[profile.release]
lto = true                # link-time optimization
codegen-units = 1         # better optimization, slower compile
panic = "abort"           # smaller binary, no unwinding tables

Parallelize when it's actually CPU-bound: rayon's par_iter() (module 17).

What doesn't need optimizing

Iterator chains, generics, match, small structs passed by value, &str slicing — these are already zero-cost. Don't uglify code for them.


How to actually make Rust code faster

In order, and the order matters more than any individual technique:

1. Make sure you are measuring a release build. Debug builds are frequently ten times slower. Every benchmark runs with --release, no exceptions — this alone explains most "Rust is slow" reports.

2. Profile before changing anything. cargo flamegraph, or criterion for a specific function. The bottleneck is somewhere you did not expect; it always is.

3. Then look for the usual suspects, roughly in order of how often they are the answer:

SuspectThe fix
.clone() in a hot loopBorrow instead
Allocating inside a loopVec::with_capacity before it, or reuse one buffer
String concatenation in a loopwrite! into one buffer, or .join()
Bounds checks in a tight numeric loopIterators instead of indexing — the check is elided
Genuinely parallel CPU workrayon's par_iter() (module 17)
Dynamic dispatch on a hot pathGenerics instead of dyn (module 12)

4. Measure again. If it did not get faster, revert it. Code made uglier for no measured gain is a straight loss, and reverting is not a failure — it is the process working.

The habit that separates the two kinds of optimisation: keep the benchmark. Once you have one, every future clever idea has to prove itself, and you stop guessing forever.

Analogy — measure the traffic before widening the road

Optimising code you have not profiled is widening a road because it feels congested. Measure first: the jam is almost never where it feels like it is, and in Rust it is usually an allocation in a loop or a clone() that borrowing would have removed. Reach for the profiler before you reach for cleverness — and keep the benchmark, so tomorrow's clever change has to prove itself.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
idiomaticWritten the way the language's community writes it — recognisable to other Rust developers.
newtypeA one-field wrapper struct giving a distinct type: struct UserId(u32).
AsRef / IntoTraits for accepting flexible input types in an API.
stringly typedUsing strings where an enum or a newtype belongs.
profilingMeasuring where a program actually spends its time.
flamegraphA visualisation of profiled time, by call stack.
criterionThe standard benchmarking crate for stable Rust.
release build--release, with optimisations on. The only meaningful thing to measure.
LTOLink-time optimisation — cross-crate optimisation at link time.
bounds checkThe runtime check that an index is in range. Iterators avoid it.
capstoneA project exercising the whole course rather than one topic.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
"Rust is slower than my Python version"Almost certainly a debug build.Rebuild with --release and measure again.
Cannot decide between &str and String in a signatureThe default answer exists.Take &str, return String. Deviate only for a measured reason.
.clone() scattered through the codeA borrow-checker workaround that became a habit.Take each one and try &. Most will compile.
The capstone feels too large to startNormal — it is the first project-sized thing you have built.Build the smallest end-to-end version that runs, then add one feature at a time.
An optimisation made no differenceYou were not looking at the bottleneck.Revert it and profile properly.

Now make it stick: work through the drills for this module — and then build the capstones.