agentleFS
botirkhaltaevbotirkhaltaev/botir-skills/skills/rust-type-system/SKILL.md

rust-type-system

Skill4 starsChanged 3 months agoApache-2.0View on GitHub

Deep understanding of Rust's type system including generics, traits, trait objects, associated types, GATs, and type-level programming. Use when designing generic APIs, choosing between static and dynamic dispatch, implementing complex trait bounds, or encoding invariants in types.

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 3 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Rule: Use associated types when there's one natural implementation.

    line 124
  2. Very specific:

    All methods have &self or &mut self receiver (not self or no self)

    line 129
  3. Very specific:

    No methods return Self

    line 130
  4. Distinctive:

    No methods have generic type parameters

    line 131
  5. Distinctive:

    No associated functions (methods without self)

    line 132

≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Rust Type System

Based on Effective Rust, The Rust Reference, and The Rust Programming Language.

When to Use This Skill

  • Choosing between generics (monomorphization) and trait objects (dynamic dispatch)
  • Writing complex where clauses and trait bounds
  • Using associated types vs type parameters
  • Understanding object safety rules
  • Implementing GATs (Generic Associated Types)
  • Using PhantomData for type-level programming
  • Encoding invariants with the type system

Generics vs Trait Objects

Generics (Static Dispatch)

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for item in &list[1..] {
        if item > largest { largest = item; }
    }
    largest
}
  • Monomorphized: separate code generated for each concrete type
  • Zero runtime cost (no vtable indirection)
  • Larger binary (code duplication)
  • Type known at compile time

Trait Objects (Dynamic Dispatch)

fn draw_all(shapes: &[&dyn Draw]) {
    for shape in shapes {
        shape.draw();  // vtable lookup at runtime
    }
}
  • Single code path for all types
  • Slight runtime cost (vtable pointer + indirect call)
  • Smaller binary
  • Type erased — heterogeneous collections possible

Decision Matrix

FactorGenericsTrait Objects
PerformanceFaster (inlined)Indirect call overhead
Binary sizeLargerSmaller
Heterogeneous collectionsNoYes
Compile timeLongerShorter
Downcasting possibleNo (type erased)Via Any

Trait Bounds

Syntax Variants

// Where clause (preferred for complex bounds)
fn process<T, U>(x: T, y: U) -> String
where
    T: Display + Clone + Send,
    U: Into<String> + Debug,
{ ... }

// Inline bounds (for simple cases)
fn print<T: Display>(val: T) { println!("{val}"); }

// impl Trait (argument position — sugar for generics)
fn process(val: impl Display + Clone) { ... }

// impl Trait (return position — opaque type)
fn make_iter() -> impl Iterator<Item = u32> { (0..10).filter(|x| x % 2 == 0) }

Useful Bound Combinations

T: Send + Sync + 'static      // thread-safe, no borrows
T: Default + Clone             // can create and duplicate
T: Serialize + DeserializeOwned  // full serde support
T: AsRef<Path>                 // accepts &str, String, PathBuf, &Path
T: Into<String>                // accepts String, &str (via allocation)

Associated Types vs Type Parameters

Associated Types (one implementation per type)

trait Iterator {
    type Item;  // determined by the implementor
    fn next(&mut self) -> Option<Self::Item>;
}

impl Iterator for Counter {
    type Item = u32;  // Counter always yields u32
    fn next(&mut self) -> Option<u32> { ... }
}

Type Parameters (multiple implementations per type)

trait From<T> {
    fn from(val: T) -> Self;
}

// String can implement From<&str>, From<Vec<u8>>, etc.
impl From<&str> for String { ... }
impl From<Vec<u8>> for String { ... }

Rule: Use associated types when there's one natural implementation. Use type parameters when a type could have multiple.

Object Safety

A trait is object-safe (can be used as dyn Trait) if:

  1. All methods have &self or &mut self receiver (not self or no self)
  2. No methods return Self
  3. No methods have generic type parameters
  4. No associated functions (methods without self)
  5. No where Self: Sized bounds on the trait itself
// Object-safe
trait Draw {
    fn draw(&self);
    fn bounds(&self) -> Rect;
}

// NOT object-safe (returns Self)
trait Clone {
    fn clone(&self) -> Self;
}

// Workaround: separate object-safe subset
trait CloneBox {
    fn clone_box(&self) -> Box<dyn CloneBox>;
}

Generic Associated Types (GATs)

trait LendingIterator {
    type Item<'a> where Self: 'a;
    fn next(&mut self) -> Option<Self::Item<'_>>;
}

// Can return references to internal state
impl LendingIterator for WindowsMut {
    type Item<'a> = &'a mut [u8] where Self: 'a;
    fn next(&mut self) -> Option<&mut [u8]> { ... }
}

PhantomData

Mark type parameters that don't appear in fields:

use std::marker::PhantomData;

struct Slice<'a, T> {
    ptr: *const T,
    len: usize,
    _lifetime: PhantomData<&'a T>,  // owns a &'a T conceptually
}

// Typestate marker
struct Authenticated;
struct Anonymous;
struct Client<State> {
    token: Option<String>,
    _state: PhantomData<State>,
}

Sealed Traits

Prevent external implementations:

mod private {
    pub trait Sealed {}
}

pub trait MyTrait: private::Sealed {
    fn method(&self);
}

// Only types in this crate can implement MyTrait
pub struct MyType;
impl private::Sealed for MyType {}
impl MyTrait for MyType { fn method(&self) { } }

Reference Map

  • references/generics-monomorphization.md — generic functions, methods, impl blocks
  • references/traits-bounds.md — trait bounds, supertraits, blanket impls, coherence
  • references/advanced-types.md — GATs, existential types, type-level programming

Key References

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.