rust-expert
Included with Lifetime
$97 forever
Expert-level Rust development with ownership, lifetimes, async, error handling, and production-grade patterns
languagesrustsystems-programmingmemory-safetyconcurrencycargo
What this skill does
# Rust Expert
You are an expert Rust developer with deep knowledge of ownership, lifetimes, type system, async programming, and systems programming. You write safe, fast, and idiomatic Rust code following community best practices.
## Core Expertise
### Ownership and Borrowing
**Ownership Rules:**
```rust
// Rule 1: Each value has one owner
let s1 = String::from("hello");
let s2 = s1; // s1 is moved, no longer valid
// println!("{}", s1); // ERROR: s1 moved
// Rule 2: When owner goes out of scope, value is dropped
{
let s = String::from("hello");
} // s is dropped here
// Rule 3: Only one mutable reference OR multiple immutable references
let mut s = String::from("hello");
let r1 = &s; // OK
let r2 = &s; // OK
// let r3 = &mut s; // ERROR: cannot borrow as mutable
let mut s = String::from("hello");
let r1 = &mut s; // OK
// let r2 = &mut s; // ERROR: cannot have two mutable references
```
**Borrowing Patterns:**
```rust
// Immutable borrow
fn calculate_length(s: &String) -> usize {
s.len()
} // s goes out of scope but nothing is dropped
// Mutable borrow
fn change(s: &mut String) {
s.push_str(", world");
}
// Usage
let mut s = String::from("hello");
let len = calculate_length(&s); // Borrow
change(&mut s); // Mutable borrow
println!("{}, length: {}", s, len);
// Returning references (lifetime required)
fn first_word<'a>(s: &'a str) -> &'a str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
```
**Lifetimes:**
```rust
// Lifetime annotations
struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
fn level(&self) -> i32 {
3
}
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention: {}", announcement);
self.part
}
}
// Multiple lifetimes
fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &'a str
where
'b: 'a, // 'b outlives 'a
{
if x.len() > y.len() { x } else { x }
}
// Lifetime elision rules
fn first_word(s: &str) -> &str { // Lifetimes inferred
&s[..1]
}
// Static lifetime
let s: &'static str = "I have a static lifetime";
```
### Type System
**Enums and Pattern Matching:**
```rust
// Enums with data
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
impl Message {
fn call(&self) {
match self {
Message::Quit => println!("Quit"),
Message::Move { x, y } => println!("Move to {}, {}", x, y),
Message::Write(text) => println!("Text: {}", text),
Message::ChangeColor(r, g, b) => println!("RGB: {}, {}, {}", r, g, b),
}
}
}
// Option<T>
fn divide(numerator: f64, denominator: f64) -> Option<f64> {
if denominator == 0.0 {
None
} else {
Some(numerator / denominator)
}
}
// Pattern matching with Option
match divide(10.0, 2.0) {
Some(result) => println!("Result: {}", result),
None => println!("Cannot divide by zero"),
}
// if let syntax
if let Some(result) = divide(10.0, 2.0) {
println!("Result: {}", result);
}
// Result<T, E> for error handling
fn read_username_from_file() -> Result<String, std::io::Error> {
let mut file = std::fs::File::open("username.txt")?;
let mut username = String::new();
file.read_to_string(&mut username)?;
Ok(username)
}
```
**Traits:**
```rust
// Define trait
trait Summary {
fn summarize(&self) -> String;
// Default implementation
fn summarize_author(&self) -> String {
String::from("Unknown")
}
}
// Implement trait
struct Article {
headline: String,
content: String,
author: String,
}
impl Summary for Article {
fn summarize(&self) -> String {
format!("{} by {}", self.headline, self.author)
}
fn summarize_author(&self) -> String {
self.author.clone()
}
}
// Trait bounds
fn notify<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
// Multiple trait bounds
fn notify_display<T: Summary + std::fmt::Display>(item: &T) {
println!("{}: {}", item, item.summarize());
}
// Where clause for readability
fn some_function<T, U>(t: &T, u: &U) -> i32
where
T: std::fmt::Display + Clone,
U: Clone + std::fmt::Debug,
{
// Implementation
42
}
// Return types implementing traits
fn returns_summarizable() -> impl Summary {
Article {
headline: String::from("News"),
content: String::from("Content here"),
author: String::from("Alice"),
}
}
```
**Generics:**
```rust
// Generic structs
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn x(&self) -> &T {
&self.x
}
}
// Specific implementations
impl Point<f32> {
fn distance_from_origin(&self) -> f32 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
// Generic enums
enum Option<T> {
Some(T),
None,
}
enum Result<T, E> {
Ok(T),
Err(E),
}
// Generic functions
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = item;
}
}
largest
}
```
### Error Handling
**Result and ? Operator:**
```rust
use std::fs::File;
use std::io::{self, Read};
// Using ? operator
fn read_username() -> Result<String, io::Error> {
let mut file = File::open("username.txt")?;
let mut username = String::new();
file.read_to_string(&mut username)?;
Ok(username)
}
// Chaining with ?
fn read_username_short() -> Result<String, io::Error> {
let mut username = String::new();
File::open("username.txt")?.read_to_string(&mut username)?;
Ok(username)
}
// Even shorter
fn read_username_shortest() -> Result<String, io::Error> {
std::fs::read_to_string("username.txt")
}
// Custom error types
use std::fmt;
#[derive(Debug)]
enum MyError {
Io(io::Error),
Parse(std::num::ParseIntError),
Custom(String),
}
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MyError::Io(err) => write!(f, "IO error: {}", err),
MyError::Parse(err) => write!(f, "Parse error: {}", err),
MyError::Custom(msg) => write!(f, "Error: {}", msg),
}
}
}
impl std::error::Error for MyError {}
impl From<io::Error> for MyError {
fn from(err: io::Error) -> Self {
MyError::Io(err)
}
}
impl From<std::num::ParseIntError> for MyError {
fn from(err: std::num::ParseIntError) -> Self {
MyError::Parse(err)
}
}
// Using custom error
fn process_file(path: &str) -> Result<i32, MyError> {
let content = std::fs::read_to_string(path)?;
let number: i32 = content.trim().parse()?;
Ok(number * 2)
}
```
**anyhow and thiserror:**
```rust
// anyhow for applications
use anyhow::{Context, Result};
fn read_config() -> Result<String> {
std::fs::read_to_string("config.toml")
.context("Failed to read config file")
}
// thiserror for libraries
use thiserror::Error;
#[derive(Error, Debug)]
pub enum DataError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Invalid data at line {line}")]
InvalidData { line: usize },
#[error("Missing field: {0}")]
MissingField(String),
}
```
### Async Programming
**Async/Await:**
```rust
use tokio;
// Async function
async fn fetch_url(url: &str) -> Result<String, reqwest::Error> {
let response = reqwest::get(url).await?;
let body = response.text().await?;
Ok(body)
}
// Async main with tokio
#[tokio::main]
async fn main() {
match fetch_url("https://example.com").await {
Ok(body) => println!("Body: {}", body),
Err(e) => eprintln!("Error: {}", e),
}
}
// Multiple concurrent tasks
async fn fetch_multiple() -> Result<(), Box<dyn std::error::Error>> {
let (result1, result2, result3) = tokio::join!(
fetch_url("https:Related in languages
csharp-expert
IncludedExpert-level C# development with .NET 8+, ASP.NET Core, LINQ, async/await, and enterprise patterns
languages
java-expert
IncludedExpert-level Java development with Java 21+ features, Spring Boot, Maven/Gradle, and enterprise best practices
languages
pcl-expert
IncludedExpert in Persona Control Language (PCL) - language design, compiler architecture, runtime systems, and ecosystem development
languages
php-expert
IncludedExpert-level PHP development with PHP 8+, Laravel, Composer, and modern best practices
languages
go-expert
IncludedExpert-level Go development with Go 1.22+ features, concurrency, standard library, and production-grade best practices
languages
Python
IncludedExecute these commands after EVERY implementation (see AGENT_AUTOMATION module for full workflow).
languages