localhost.run blog

Quick experiments with cargo examples

· rust, cargo, workflow

You want to try something: a new crate, a quick HTTP endpoint, a different way of doing a thing your app already does. The usual options are both a bit wrong. A new scratch project means copying code over and losing it afterwards. Adding the crate to your real app means your release build now depends on something you were only trying out.

Cargo has a third option built in: examples.

The mechanism

Any .rs file in a package’s examples/ directory is a small program in its own right. Cargo finds it automatically, and you run it by name:

cargo run --example hello_experiment

Two things make examples good for experiments:

Hello, experiment

Start with an app that has no dependencies at all:

cargo new greeter && cd greeter
// src/main.rs
fn main() {
    println!("hello from the release build");
}

Now say you want to try serving something over HTTP. Add the crates as dev-dependencies:

cargo add --dev axum
cargo add --dev tokio --features rt-multi-thread,macros,net

Cargo.toml now looks like this:

[dependencies]

[dev-dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net"] }

Create examples/hello_experiment.rs:

use axum::{Router, routing::get};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "hello, experiment\n" }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    println!("listening on http://localhost:3000");
    axum::serve(listener, app).await.unwrap();
}

Run it:

cargo run --example hello_experiment
curl localhost:3000
hello, experiment

Want someone else to try it? Put it on the internet for a while:

ssh -R 80:localhost:3000 localhost.run

The release build doesn’t know it’s there

Build the release:

cargo build --release
   Compiling greeter v0.1.0
    Finished `release` profile [optimized] target(s) in 0.31s

Only greeter is compiled. Axum, tokio and everything they pull in are left out. cargo tree agrees:

cargo tree -e normal
greeter v0.1.0

That’s the whole dependency tree of what you ship.

Experiments in parallel with release work

Because the experiment lives in the repo, you can commit it like any other code:

One thing to know: cargo test builds every example, so that examples don’t silently stop compiling. A broken experiment fails cargo test (but never cargo build --release). Keep experiments compiling before you merge them, the same as any other code.

Summary

See the cargo run documentation for the full set of options.