All skills
apollographql avatar

/rust-best-practices

@13ff457 official
by Apollo GraphQLapollographql/skills115 stars
13

Guide for writing idiomatic Rust code based on Apollo GraphQL's best practices handbook. Use this skill when: (1) writing new Rust code or functions, (2) reviewing or refactoring existing Rust code, (3) deciding between borrowing vs cloning or ownership patterns, (4) implementing error handling with Result types, (5) optimizing Rust code for performance, (6) writing tests or documentation for Rust projects.

Use this Skill: https://skilld.dev/gh/apollographql/skills/rust-best-practices

This session only. Nothing lands on disk.

referenceschapter_07.md

≈2k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Chapter 7 - Type State Pattern

Models state at compile time, preventing bugs by making illegal states unrepresentable. It takes advantage of the Rust generics and type system to create sub-types that can only be reached if a certain condition is achieved, making some operations illegal at compile time.

Recently it became the standard design pattern of Rust programming. However, it is not exclusive to Rust, as it is achievable and has inspired other languages to do the same swift and typescript.

7.1 What is Type State Pattern?

Type State Pattern is a design pattern where you encode different states of the system as types, not as runtime flags or enums. This allows the compiler to enforce state transitions and prevent illegal actions at compile time. It also improves the developer experience, as developers only have access to certain functions based on the state of the type.

Invalid states become compile errors instead of runtime bugs.

7.2 Why use it?

  • Avoids runtime checks for state validity. If you reach certain states, you can make certain assumptions of the data you have.
  • Models state transitions as type transitions. This is similar to a state machine, but in compile time.
  • Prevents data misuse, e.g. using uninitialized objects.
  • Improves API safety and correctness.
  • The phantom data field is removed after compilation so no extra memory is allocated.

7.3 Simple Example: File State

Github Example

use std::{io, path::{Path, PathBuf}};

struct FileNotOpened;
struct FileOpened;

#[derive(Debug)]
struct File<State> {
    /// Path to the opened file
    path: PathBuf,
    /// Open `File` handler
    handle: Option<std::fs::File>,
    /// Type state manager
    _state: std::marker::PhantomData<State>
}

impl File<FileNotOpened> {
    /// `open` is the only entry point for this struct.
    /// * When called with a valid path, it will return a `File<FileOpened>` with a valid `handler` and `path`
    /// * `open` serves as an alternative to `new` and `defaults` methods (usable when your struct needs valid data to exist).
    fn open(path: &Path) -> io::Result<File<FileOpened>> {
        // If file is invalid, it will return `std::io::Error`
        let file = std::fs::File::open(path)?;
        Ok(
            File {
                path: path.to_path_buf(),
                // Always valid
                handle: Some(file),
                _state: std::marker::PhantomData::<FileOpened>
            }
        )
    }
}

impl File<FileOpened> {
    /// Reads the content of the `File` as a `String`.
    /// `read` can only be called by state `File<FileOpened>`
    fn read(&mut self) -> io::Result<String> {
        use io::Read;

        let mut content = String::new();
        let Some(handle)=  self.handle.as_mut() else {
            unreachable!("Safe to unwrap as state can only be reached when file is open");
        };
        handle.read_to_string(&mut content)?;
        Ok(content)
    }

    /// Returns the valid path buffer.
    fn path(&self) -> &PathBuf {
        &self.path
    }
}

7.4 Real-World Examples

Builder Pattern with Compile-Time Guarantees

Forces the user to set required fields before calling .build().

Github Example

A type-state pattern can have more than one associated states:

use std::marker::PhantomData;

struct Unset;
struct Set;

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
    email: Option<String>,
}

struct Builder<NameState = Unset, AgeState = Unset> {
    name: Option<String>,
    age: u8,
    email: Option<String>,
    _maker_state: PhantomData<(NameState, AgeState)>,
}

impl Builder<Unset, Unset> {
    const fn new() -> Self {
        Self { name: None, age: 0, email: None, _maker_state: PhantomData }
    }
}

impl<NameState> Builder<NameState, Unset> {
    fn age(self, age: u8) -> Builder<NameState, Set> {
        Builder { age, name: self.name, email: self.email, _maker_state: PhantomData }
    }
}

impl<AgeState> Builder<Unset, AgeState> {
    fn name(self, name: String) -> Builder<Set, AgeState> {
        Builder { name: Some(name), age: self.age, email: self.email, _maker_state: PhantomData }
    }
}

impl<NameState, AgeState> Builder<NameState, AgeState> {
    fn email(self, email: String) -> Self {
        Self { name: self.name, age: self.age, email: Some(email), _maker_state: PhantomData }
    }
}

impl Builder<Set, Set> {
    fn build(self) -> Person {
        Person {
            name: self.name.unwrap_or_else(|| unreachable!("Name is guaranteed to be set")),
            age: self.age,
            email: self.email,
        }
    }
}

Although a bit more verbose than a usual builder, this guarantees that all necessary fields are present (note that e-mail is optional field only present in the final builder).

Usage:
// ✅ Valid cases
let person: Person = Builder::new().name("name".to_string()).age(30).build();
let person: Person = Builder::new().age(30).name("name".to_string()).build();
let person: Person = Builder::new().age(30).name("name".to_string()).email("myself@email.com".to_string()).build();

// ❌ Invalid cases
let person: Person = Builder::new().name("name".to_string()).build(); // ❌ Compile error: Age required to `build`
let person: Person = Builder::new().age(30).build(); // ❌ Compile error:  Name required to `build`
let person: Person = Builder::new().age(30).email("myself@email.com".to_string()).build(); // ❌ Compile error:  Name required to `build`
let person: Person = Builder::new().age(10).age(15); // ❌ Compile error:  Age was already set
let person: Person = Builder::new().build();// ❌ Compile error:  Name and Age required to `build`

Crates implementing Builder pattern

Some libraries are already implementing the builder pattern, like bon-rs

Network Protocol State Machine

Illegal transitions like sending a message before connecting simply don't compile:

// Mock example
struct Disconnected;
struct Connected;

struct Client<State> {
    stream: Option<std::net::TcpStream>,
    _state: std::marker::PhantomData<State>
}

impl Client<Disconnected> {
    fn connect(addr: &str) -> std::io::Result<Client<Connected>> {
        let stream = std::net::TcpStream::connect(addr)?;
        Ok(Client {
            stream: Some(stream),
            _state: std::marker::PhantomData::<Connected>
        })
    }
}

impl Client<Connected> {
    fn send(&mut self, msg: &str) {
        use std::io::Write;
        let Some(stream) = self.stream.as_mut() else {
            unreachable!("Stream is guaranteed to be set");
        };
        stream.write_all(msg.as_bytes())
    }
}

7.5 Pros and Cons

✅ Use Type-State Pattern When:

  • You want compile-time state safety.
  • You need to enforce API constraints.
  • You are writing a library/crate that is heavily dependent on variants.
  • You want to replace runtime booleans or enums with type-safe code paths.
  • You need compile time correctness.

❌ Avoid it when:

  • Writing trivial states like enums.
  • Don't need type-safety.
  • When it leads to overcomplicated generics.
  • When runtime flexibility is required.

🚨 Downsides and Cautions

  • Can lead to more verbose solutions.
  • Can lead to complex type signatures.
  • May require unsafe to return variant outputs based on different states.
  • May require a bunch of duplication (e.g. same struct field reused).
  • PhantomData is not intuitive for beginners and can feel a bit hacky.

Use this pattern when it saves bugs, increases safety or simplifies logic, not just for cleverness.

Source: SKILL.md on GitHub

No alerts3d5 checks · Risk SAFE
  • Gen Agent Trust Hub3d

    This skill provides a comprehensive guide to idiomatic Rust development based on Apollo GraphQL's best practices. It covers coding styles, error handling, performance optimization, and testing procedures using standard ecosystem tools.

  • Socket3d

    No alerts

  • Snyk3d

    Risk: LOW · No issues

  • Runlayer6mo

    1/10 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 13ff457. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 3 days ago
What it can do
Runs commands
compatibility
Rust 1.70+, Cargo
metadata
{
  "author": "apollographql",
  "version": "1.1.2"
}
All 1 allowed tools
Bash(cargo:*) Bash(rustc:*) Bash(rustfmt:*) Bash(clippy:*) Read Write Edit Glob Grep

README badge

README badge for apollographql/skills/rust-best-practices

Guides idiomatic Rust code review and writing using Apollo GraphQL's best practices handbook, covering ownership patterns, error handling, performance profiling, testing conventions, and type-state patterns. Use when writing new Rust, refactoring existing code, deciding between borrowing vs cloning, or implementing error handling and performance optimizations.

Generated from the current SKILL.md.

Does this skill cover async Rust patterns?
The skill references Apollo's best practices handbook which covers core ownership, borrowing, error handling, testing, and type patterns, but async-specific guidance is not listed in the chapter references provided.
Can I use this skill to lint my existing codebase?
Yes. The skill includes Clippy configuration and linting best practices, with specific commands like `cargo clippy --all-targets --all-features --locked -- -D warnings` to identify issues in your code.
Does this skill recommend anyhow or thiserror for error handling?
Yes. The skill specifies using `thiserror` for library errors and `anyhow` for binaries only, and advises never using `unwrap()` or `expect()` outside tests.
What Rust version does this require?
The skill requires Rust 1.70 or later and Cargo.
Does this cover the type state pattern?
Yes. Chapter 7 covers the type state pattern for encoding valid states in the type system to catch invalid operations at compile time, with a code example showing Connection states.

Generated from the current SKILL.md. These answers refresh after source changes.