跳至正文
OpenAgentSkill
浏览已开放 · 目录记录日期 2026-11-21 · 自动更新和账户服务暂时关闭。
设计与 UI

idiomatic-rust

Write Rust that reads like Rust — iterator pipelines over index loops, From/Into over ad-hoc converters, derives over hand-written impls, newtypes over bare primitives. Use when writing new Rust, when reviewing Rust that reads like a translation from another language, when reaching for a classic design pattern (strategy, command, visitor) or a try/finally cleanup in Rust, when naming a constructor, accessor, iterator, or error type, or when the user asks how to make Rust code more idiomatic or less repetitive.

rewrite-rs · 已有静态检查记录

安装与使用

运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。

npx skills add rewrite-rs/skills --skill idiomatic-rust

技能说明


name: idiomatic-rust description: Write Rust that reads like Rust — iterator pipelines over index loops, From/Into over ad-hoc converters, derives over hand-written impls, newtypes over bare primitives. Use when writing new Rust, when reviewing Rust that reads like a translation from another language, when reaching for a classic design pattern (strategy, command, visitor) or a try/finally cleanup in Rust, when naming a constructor, accessor, iterator, or error type, or when the user asks how to make Rust code more idiomatic or less repetitive.

Idiomatic Rust

This skill is about expression: what form does a Rust reader expect to see?

Three principles sit under every choice here. Readability beats writeability: pick the form that is quickest to read, even if it is longer to type. Uniformity beats cleverness: when similar code takes the same shape everywhere, a tool or a scripted sweep can change it in one pass, and rustfmt settles layout so reviews skip it. And consistency with the ecosystem beats local taste: follow the conventions the Rust project and the standard library already set, except where the repo has a settled convention that differs.

The shape of idiomatic Rust

Prefer expressions over statements: a match that returns a value beats one that assigns to a let mut in every arm, and a chain that produces the answer beats a flag variable set in a loop and checked after it — let the type system carry invariants instead of runtime checks. let ... else keeps an early return at the top instead of drifting the happy path rightward under a nested if let; matches! is the boolean test on a pattern. If-let chains compose conditions where the toolchain supports them — a recent edition, so check the repo MSRV first.

Iterators

Reach for the iterator pipeline before the index loop — for i in 0..v.len() { ... v[i] ... } almost always has an iterator equivalent, and the iterator version fails to compile on bad bounds instead of panicking at runtime. Think of a pipeline as a source (iter, a range), then adapters that reshape lazily (filter, map, take, zip), then one consumer that drives it and produces a result (collect, sum, fold, find, any). Nothing runs until the consumer does. The pipeline says what the result is; the loop with a mutable accumulator says how to build it, and the first is what a reader wants. Collect into the type you want, not a Vec you then convert:

// Reads like a translation.
let mut names = Vec::new();
for user in &users {
    names.push(user.name.clone());
}

// Reads like Rust.
let names: Vec<String> = users.iter().map(|u| u.name.clone()).collect();

collect also targets HashMap, HashSet, String, and Result<Vec<_>, _> — that last is how ? composes with iteration.

use std::num::ParseIntError;

fn parse_all(lines: &[&str]) -> Result<Vec<i64>, ParseIntError> {
    lines.iter().map(|line| line.parse::<i64>()).collect::<Result<Vec<_>, _>>()
}

Prefer the plain for loop when the body has real side effects or an early exit a combinator would obscure, and also when the body is long or does more than one job — a closure that filters, logs, and accumulates reads better as a loop with named steps. Clarity beats iterator purity.

Conversions

When one type can be built from another, implement From — Into comes free through the blanket impl, so never write both directions by hand. Never implement Into or TryInto directly either: implement From or TryFrom and the blanket impl supplies the other side. When the conversion can fail, implement TryFrom instead of From plus a panic or a sentinel value.

In a generic bound, T: Into<Foo> accepts every type with a From impl (since the blanket impl supplies Into), but not a type that only has TryFrom; ask for TryInto<Foo> when failure is acceptable to the caller. Prefer From as the thing you implement and Into as the thing you ask for. Absence is Option, never a magic value such as -1 or an empty string, and a fallible result is Result. The inherent constructor that may sit beside an important From impl is covered in NAMING.md.

Direction matters for numbers: widening is lossless, so u32::from(x_u16) exists (impl From<u16> for u32), while narrowing is fallible and gets TryFrom, never a From<u32> for u16 that would truncate.

fn widen(x: u16) -> u32 {
    u32::from(x)
}

fn narrow(x: u32) -> Option<u16> {
    u16::try_from(x).ok()
}
struct Celsius(f64);
struct Fahrenheit(f64);

impl From<Celsius> for Fahrenheit {
    fn from(c: Celsius) -> Self {
        Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
    }
}

Derives before hand-written impls

Reach for #[derive(Debug, Clone, PartialEq, Default, Hash)] before writing it by hand — a derived impl is generated from the actual fields, so it stays in sync as the struct changes. Write the manual version only when the derive would be wrong:

  • A Default that must preserve an invariant the field-wise default breaks (a Percentage summing to 100, not zero per field).
  • A Debug that must redact a secret field (an API key, a password) rather than print it.
  • PartialEq where logically-equal values can differ in a field that shouldn't count (a cached hash, a timestamp).

The comparison and copy traits come with rules of their own:

  • Copy suits plain data a few words wide, where duplicating the bits is both correct and inexpensive. Skip it for a large type or one that owns a resource; adding it is a promise that removing it later breaks every caller.
  • Clone is skipped for a type that stands for unique access to something (a lock guard, a file handle) and for secret key material, where a silent duplicate is a leak.
  • Eq goes with PartialEq for any type whose equality is total. Never for a type with floats, since NaN != NaN.
  • Hash must agree with Eq: values that compare equal hash eq
阅读完整来源 ↗