Rust snippets

Keep your team's Rust snippets in one base.

Rust teams converge on the same idioms — error enums with thiserror, newtypes that parse instead of validate, tokio timeouts around every await — but the knowledge usually lives in one senior dev's head and a scattering of half-remembered blog posts. The-Snip gives those idioms a reviewed home: searchable snippets with real Rust highlighting, Markdown docs for the crate decisions and unsafe justifications, and saved API calls beside the client code. Your agents read the same base over REST and MCP, so the borrow-checker-appeasing pattern your team settled on is the one they reuse — and what they file back waits for human review.

Rust snippets worth keeping

Result-returning main

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let config = std::fs::read_to_string("config.toml")?;
    println!("{config}");
    Ok(())
}

The ? operator works in main once it returns Result — no unwrap pyramids in binaries, and errors print their Display chain on exit.

Error enum with thiserror

use thiserror::Error;

#[derive(Debug, Error)]
pub enum AppError {
    #[error("not found: {0}")]
    NotFound(String),
    #[error("invalid input: {0}")]
    Invalid(String),
    #[error("io error")]
    Io(#[from] std::io::Error),
}

One error type per crate boundary, with #[from] doing the conversions. Callers match on variants instead of string-parsing a Box<dyn Error>.

Parse, don't validate — newtype

pub struct Email(String);

impl Email {
    pub fn parse(s: String) -> Result<Self, String> {
        if s.contains('@') && !s.trim().is_empty() {
            Ok(Self(s))
        } else {
            Err(format!("invalid email: {s}"))
        }
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

Once constructed, an Email is valid everywhere it flows — the type system remembers so your functions don't have to re-check. The private field forces construction through parse.

Timeout any future (tokio)

use tokio::time::{timeout, Duration};

let res = timeout(Duration::from_secs(5), fetch_user(id)).await;
match res {
    Ok(Ok(user)) => println!("{user:?}"),
    Ok(Err(e)) => eprintln!("fetch failed: {e}"),
    Err(_) => eprintln!("timed out after 5s"),
}

The double Result is the point: outer Err means the deadline fired, inner Err means the operation itself failed. Handle them differently — one is load, the other is a bug.

Buffered line reader

use std::fs::File;
use std::io::{BufRead, BufReader};

fn lines(path: &str) -> std::io::Result<impl Iterator<Item = String>> {
    let file = File::open(path)?;
    Ok(BufReader::new(file).lines().map_while(Result::ok))
}

File::open alone reads unbuffered — fine for a config file, brutal for a million-line log. BufReader plus map_while is the standard streaming shape.

Questions, answered.

Does the highlighting handle lifetimes, macros and generics?

Yes — The-Snip uses the same TextMate grammar VS Code uses for Rust, rendered server-side. Lifetimes, derive macros, format! interpolation and where-clauses all tokenize correctly.

Can agents file Rust snippets back into the base?

Yes — over REST or the hosted MCP server; filing is an agent write, which needs the one Pro & Team plan ($8/user/month), while reads are free on every plan. An agent that works out a tricky pattern files it with create_snippet; it lands in review, and a human decides whether it becomes canon.

Where do crate decisions and unsafe justifications go?

Markdown docs, next to the snippets. Write "why we chose sqlx over diesel" once, link it from the relevant snippets with [[wikilinks]], and both new hires and agents find the reasoning with the code.

Can I attach expected output to a snippet?

Yes — every snippet can carry a sample-output block. For error-handling patterns, teams paste the compiler error the pattern avoids; nothing communicates faster to the next reader.

Is there a free plan?

Yes — 25 items, no card, and read-only agent access over REST and MCP. The paid plan is Pro & Team at $8/user/month ($80/user/year, two months free) and adds unlimited items, export, agent writes (create and update), workspaces and review.

Start your base — free.

Free: 25 items, no card. Pro & Team: $8/user/mo — unlimited items, REST API, review workflow, and the hosted MCP server.