Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Rust Best Practices Guide

БесплатноБез исполняемых скриптовНе проверен

A comprehensive guide to modern Rust best practices covering style, error handling, performance, concurrency, project organization, dependency management…

mosif16от mosif16★ 18 звёзд на GitHub

Об этом скилле

Instructions

General Coding Conventions and Style

  • Use Standard Naming Conventions: Follow Rust’s naming idioms for all identifiers. Type names (structs, enums, traits) and enum variants use UpperCamelCase. Function, method, module, and variable names use snake_case. Constants and statics use SCREAMING_SNAKE_CASE. For example, a struct might be named UserAccount and a function process_request. Avoid acronyms in all-caps in CamelCase (use Uuid instead of UUID) and prefer full words over abbreviations. If a desired name is a reserved keyword, use a raw identifier (e.g. r#trait) or append an underscore rather than misspelling the name.

  • Code Formatting with rustfmt: Adhere to the official Rust Style Guide (largely embodied by rustfmt). Use 4 spaces for indentation and keep line width under 100 chars. Let rustfmt automatically format your code to enforce consistent style and avoid bikeshedding in code reviews. In CI, include a formatting check (cargo fmt -- --check) to reject misformatted code. This ensures a uniform style across the project, making it easier to read and contributing to community consistency.

  • Idiomatic Expressions: Embrace Rust idioms for clarity and conciseness. Favor expressions over explicit intermediate variables when possible (e.g. use let x = if cond { a } else { b }; instead of a mutable let x; with an if/else block). Leverage iterators and the ownership system to write clear code rather than low-level loops or manual memory handling when high-level constructs suffice. Write comments in complete sentences and prefer line comments (//) for clarity. Use /// doc comments for public items and include examples and usage guidance in them (see Documentation section).

  • Maintain Module Clarity: Organize modules hierarchically with clear purposes. Each file in src/ can define a module; use submodules (with their own files or a mod.rs) to logically group code. Avoid using #[path] to include files except in unusual cases – instead, follow Cargo’s conventions (e.g. src/lib.rs as the crate root, submodules in files named after the module). This makes the project structure predictable. Split large modules into sub-modules to keep files at a manageable size and to separate concerns.

  • Consistent Project Structure: Use Cargo’s idiomatic layout. A package can contain a library crate (src/lib.rs) and/or binary crates (src/main.rs for the primary binary, additional binaries in src/bin/). Prefer keeping most code in library crates so it can be tested and reused, with the main.rs just instantiating and invoking library code. For multi-crate projects, consider a Cargo workspace to share a single Cargo.lock and coordinate versions. Each crate should have a clear responsibility. For example, in a web application, you might have separate crates for the core logic, the HTTP server runtime, and utilities.

Error Handling Best Practices

  • Prefer Result for Recoverable Errors: Rust doesn’t use exceptions; instead, the standard for recoverable errors is the Result<T, E> type. Functions that can fail should return a Result, giving the caller the choice to handle the error or propagate it. Only use panic! for unrecoverable errors or violations of invariants (situations that indicate a bug). For instance, a function reading a file should return Result<Contents, IOError> rather than panicking if the file is missing. Use the ? operator to propagate errors up the call stack conveniently when you want to return the error to the caller.

  • Guidelines on panic! vs Result: Call panic! only in scenarios where no reasonable recovery exists and continuing execution would be invalid or unsafe. This includes internal logic errors, unreachable code paths, or irrecoverable state corruption. Library code in particular should avoid panicking on expected error conditions; instead, return errors so that the library user can decide how to handle them. In binaries (applications), a panic will crash the program, so reserve it for truly unrecoverable situations. Use expect/unwrap only in tests, prototypes, or in main for quick scripts, and even then prefer providing a helpful message with expect.

  • Use Error Types and Context: Define clear error types for your library using enums (each variant representing a different error case). The thiserror crate can derive the std::error::Error trait implementation for custom error types easily. For application code (binaries), use a convenient error wrapper like anyhow for simplicity. anyhow::Error is a dynamic error type that can represent any error and capture backtraces; it’s useful in main or higher-level code where fine-grained error handling isn’t needed. For example, a CLI tool’s main function can be fn main() -> Result<(), anyhow::Error> to use ? freely with different error types. With anyhow, attach context to errors using `.context("high-level descrip

Полный SKILL.md на GitHub

Установить Rust Best Practices Guide в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл Rust Best Practices Guide?

A comprehensive guide to modern Rust best practices covering style, error handling, performance, concurrency, project organization, dependency management, documentation, testing, security, and CI.

Как установить скилл Rust Best Practices Guide?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Rust Best Practices Guide запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Rust Best Practices Guide с