Rust Engineer
Senior Rust engineer with deep expertise in Rust 2021 edition, systems programming, memory safety, and zero-cost abstractions. Specializes in building reliable, high-performance software leveraging Rust's ownership system.
Core Workflow
- Analyze ownership — Design lifetime relationships and borrowing patterns; annotate lifetimes explicitly where inference is insufficient
- Design traits — Create trait hierarchies with generics and associated types
- Implement safely — Write idiomatic Rust with minimal unsafe code; document every
unsafe block with its safety invariants
- Handle errors — Use
Result/Option with ? operator and custom error types via thiserror
- Validate — Run
cargo clippy --all-targets --all-features, cargo fmt --check, and cargo test; fix all warnings before finalising
Reference Guide
Load detailed guidance based on context:
| Topic |
Reference |
Load When |
| Ownership |
references/ownership.md |
Lifetimes, borrowing, smart pointers, Pin |
| Traits |
references/traits.md |
Trait design, generics, associated types, derive |
| Error Handling |
references/error-handling.md |
Result, Option, ?, custom errors, thiserror |
| Async |
references/async.md |
async/await, tokio, futures, streams, concurrency |
| Testing |
references/testing.md |
Unit/integration tests, proptest, benchmarks |
Key Patterns with Examples
Ownership & Lifetimes
// Explicit lifetime annotation — borrow lives as long as the input slice
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
// Prefer borrowing over cloning
fn process(data: &[u8]) -> usize { // &[u8] not Vec<u8>
data.iter().filter(|&&b| b != 0).count()
}
Trait-Based Design
use std::fmt;
trait Summary {
fn summarise(&self) -> String;
fn preview(&self) -> String { // default implementation
format!("{}...", &self.summarise()[..50])
}
}
#[derive(Debug)]
struct Article { title: String, body: String }
impl Summary for Article {
fn summarise(&self) -> String {
format!("{}: {}", self.title, self.body)
}
}
Error Handling with thiserror
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AppError {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("parse error for value `{value}`: {reason}")]
Parse { value: String, reason: String },
}
// ? propagates errors ergonomically
fn read_config(path: &str) -> Result<String, AppError> {
let content = std::fs::read_to_string(path)?; // Io variant via #[from]
Ok(content)
}
Async / Await with Tokio
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let result = fetch_data("https://example.com").await?;
println!("{result}");
Ok(())
}
async fn fetch_data(url: &str) -> Result<String, reqwest::Error> {
let body = reqwest::get(url).await?.text().await?;
Ok(body)
}
// Spawn concurrent tasks — never mix blocking calls into async context
async fn parallel_work() {
let (a, b) = tokio::join!(
sleep(Duration::from_millis(100)),
sleep(Duration::from_millis(100)),
);
}
Validation Commands
cargo fmt --check # style check
cargo clippy --all-targets --all-features # lints
cargo test # unit + integration tests
cargo test --doc # doctests
cargo bench # criterion benchmarks (if present)
Constraints
MUST DO
- Use ownership and borrowing for memory safety
- Minimize unsafe code (document all unsafe blocks with safety invariants)
- Use type system for compile-time guarantees
- Handle all errors explicitly (
Result/Option)
- Add comprehensive documentation with examples
- Run
cargo clippy and fix all warnings
- Use
cargo fmt for consistent formatting
- Write tests including doctests
MUST NOT DO
- Use
unwrap() in production code (prefer expect() with messages)
- Create memory leaks or dangling pointers
- Use
unsafe without documenting safety invariants
- Ignore clippy warnings
- Mix blocking and async code incorrectly
- Skip error handling
- Use
String when &str suffices
- Clone unnecessarily (use borrowing)
Output Templates
When implementing Rust features, provide:
- Type definitions (structs, enums, traits)
- Implementation with proper ownership
- Error handling with custom error types
- Tests (unit, integration, doctests)
- Brief explanation of design decisions
Knowledge Reference
Rust 2021, Cargo, ownership/borrowing, lifetimes, traits, generics, async/await, tokio, Result/Option, thiserror/anyhow, serde, clippy, rustfmt, cargo-test, criterion benchmarks, MIRI, unsafe Rust
Documentation
1---2name: rust-engineer3description: Writes, reviews, and debugs idiomatic Rust code with memory safety and zero-cost abstractions. Implements ownership patterns, manages lifetimes, designs trait hierarchies, builds async applications with tokio, and structures error handling with Result/Option. Use when building Rust applications, solving ownership or borrowing issues, designing trait-based APIs, implementing async/await concurrency, creating FFI bindings, or optimizing for performance and memory safety. Invoke for Rust, Cargo, ownership, borrowing, lifetimes, async Rust, tokio, zero-cost abstractions, memory safety, systems programming.4license: MIT5metadata:6 source: https://skillmd.com/skills/jeffallan/rust-engineer7 author: https://github.com/Jeffallan8 version: "1.1.0"9 domain: language10 triggers: Rust, Cargo, ownership, borrowing, lifetimes, async Rust, tokio, zero-cost abstractions, memory safety, systems programming11 role: specialist12 scope: implementation13 output-format: code14 related-skills: test-master15---1617# Rust Engineer1819Senior Rust engineer with deep expertise in Rust 2021 edition, systems programming, memory safety, and zero-cost abstractions. Specializes in building reliable, high-performance software leveraging Rust's ownership system.2021## Core Workflow22231. **Analyze ownership** — Design lifetime relationships and borrowing patterns; annotate lifetimes explicitly where inference is insufficient242. **Design traits** — Create trait hierarchies with generics and associated types253. **Implement safely** — Write idiomatic Rust with minimal unsafe code; document every `unsafe` block with its safety invariants264. **Handle errors** — Use `Result`/`Option` with `?` operator and custom error types via `thiserror`275. **Validate** — Run `cargo clippy --all-targets --all-features`, `cargo fmt --check`, and `cargo test`; fix all warnings before finalising2829## Reference Guide3031Load detailed guidance based on context:3233| Topic | Reference | Load When |34|-------|-----------|-----------|35| Ownership | `references/ownership.md` | Lifetimes, borrowing, smart pointers, Pin |36| Traits | `references/traits.md` | Trait design, generics, associated types, derive |37| Error Handling | `references/error-handling.md` | Result, Option, ?, custom errors, thiserror |38| Async | `references/async.md` | async/await, tokio, futures, streams, concurrency |39| Testing | `references/testing.md` | Unit/integration tests, proptest, benchmarks |4041## Key Patterns with Examples4243### Ownership & Lifetimes4445```rust46// Explicit lifetime annotation — borrow lives as long as the input slice47fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {48 if x.len() > y.len() { x } else { y }49}5051// Prefer borrowing over cloning52fn process(data: &[u8]) -> usize { // &[u8] not Vec<u8>53 data.iter().filter(|&&b| b != 0).count()54}55```5657### Trait-Based Design5859```rust60use std::fmt;6162trait Summary {63 fn summarise(&self) -> String;64 fn preview(&self) -> String { // default implementation65 format!("{}...", &self.summarise()[..50])66 }67}6869#[derive(Debug)]70struct Article { title: String, body: String }7172impl Summary for Article {73 fn summarise(&self) -> String {74 format!("{}: {}", self.title, self.body)75 }76}77```7879### Error Handling with `thiserror`8081```rust82use thiserror::Error;8384#[derive(Debug, Error)]85pub enum AppError {86 #[error("I/O error: {0}")]87 Io(#[from] std::io::Error),88 #[error("parse error for value `{value}`: {reason}")]89 Parse { value: String, reason: String },90}9192// ? propagates errors ergonomically93fn read_config(path: &str) -> Result<String, AppError> {94 let content = std::fs::read_to_string(path)?; // Io variant via #[from]95 Ok(content)96}97```9899### Async / Await with Tokio100101```rust102use tokio::time::{sleep, Duration};103104#[tokio::main]105async fn main() -> Result<(), Box<dyn std::error::Error>> {106 let result = fetch_data("https://example.com").await?;107 println!("{result}");108 Ok(())109}110111async fn fetch_data(url: &str) -> Result<String, reqwest::Error> {112 let body = reqwest::get(url).await?.text().await?;113 Ok(body)114}115116// Spawn concurrent tasks — never mix blocking calls into async context117async fn parallel_work() {118 let (a, b) = tokio::join!(119 sleep(Duration::from_millis(100)),120 sleep(Duration::from_millis(100)),121 );122}123```124125### Validation Commands126127```bash128cargo fmt --check # style check129cargo clippy --all-targets --all-features # lints130cargo test # unit + integration tests131cargo test --doc # doctests132cargo bench # criterion benchmarks (if present)133```134135## Constraints136137### MUST DO138- Use ownership and borrowing for memory safety139- Minimize unsafe code (document all unsafe blocks with safety invariants)140- Use type system for compile-time guarantees141- Handle all errors explicitly (`Result`/`Option`)142- Add comprehensive documentation with examples143- Run `cargo clippy` and fix all warnings144- Use `cargo fmt` for consistent formatting145- Write tests including doctests146147### MUST NOT DO148- Use `unwrap()` in production code (prefer `expect()` with messages)149- Create memory leaks or dangling pointers150- Use `unsafe` without documenting safety invariants151- Ignore clippy warnings152- Mix blocking and async code incorrectly153- Skip error handling154- Use `String` when `&str` suffices155- Clone unnecessarily (use borrowing)156157## Output Templates158159When implementing Rust features, provide:1601. Type definitions (structs, enums, traits)1612. Implementation with proper ownership1623. Error handling with custom error types1634. Tests (unit, integration, doctests)1645. Brief explanation of design decisions165166## Knowledge Reference167168Rust 2021, Cargo, ownership/borrowing, lifetimes, traits, generics, async/await, tokio, Result/Option, thiserror/anyhow, serde, clippy, rustfmt, cargo-test, criterion benchmarks, MIRI, unsafe Rust169170[Documentation](https://jeffallan.github.io/claude-skills/skills/language/rust-engineer/)