mcpField
R
rust

rust

github.com/dralgorhythm开发12953 次安装14 周前更新
代码仓库

关于 rust

这项 Rust 开发技能涵盖常见项目结构、所有权与借用、错误处理、异步编程、Axum 处理器、测试及 Cargo 工具,适合作为日常开发参考。

主要功能

  1. 01项目结构指导
  2. 02所有权与借用示例
  3. 03使用 thiserror 处理错误
  4. 04Tokio 异步模式
  5. 05Axum 处理器示例
  6. 06Cargo 格式化、检查与测试

适用场景

  1. 01组织 Rust 项目
  2. 02处理应用错误
  3. 03编写 Rust 异步代码
  4. 04格式化、检查和测试代码

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/dralgorhythm/claude-agentic-framework --skill rust

安装后在 Claude Code 中输入/rust确认已加载。

README 原文English

来自项目 README

README 暂无中文译文,以下为英文原文;中文介绍见上方。

Rust Development

Project Structure

my-project/
├── Cargo.toml
├── src/
│   ├── main.rs
│   ├── lib.rs
│   └── handlers/
│       └── mod.rs
└── tests/
    └── integration.rs

Error Handling

use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("User not found: {0}")]
    NotFound(String),

    #[error("Database error: {0}")]
    Database(#[from] sqlx::Error),

    #[error("Validation error: {0}")]
    Validation(String),
}

// Using Result
async fn get_user(id: &str) -> Result<User, AppError> {
    let user = sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", id)
        .fetch_optional(&pool)
        .await?
        .ok_or_else(|| AppError::NotFound(id.to_string()))?;

    Ok(user)
}

// Using ? operator
fn process() -> Result<(), AppError> {
    let user = get_user("123")?;
    validate(&user)?;
    save(&user)?;
    Ok(())
}

Ownership & Borrowing

// Ownership transfer
fn take_ownership(s: String) {
    println!("{}", s);
} // s is dropped here

// Borrowing (immutable)
fn borrow(s: &String) {
    println!("{}", s);
}

// Mutable borrowing
fn mutate(s: &mut String) {
    s.push_str(" world");
}

// Lifetimes
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

Async with Tokio

use tokio;

#[tokio::main]
async fn main() {
    let result = fetch_data().await;
}

async fn fetch_all(urls: Vec<String>) -> Vec<Response> {
    let futures: Vec<_> = urls
        .into_iter()
        .map(|url| tokio::spawn(async move { fetch(&url).await }))
        .collect();

    let results = futures::future::join_all(futures).await;
    results.into_iter().filter_map(|r| r.ok()).collect()
}

Axum Web Handler

use axum::{
    extract::{Path, State},
    http::StatusCode,
    Json,
};

async fn get_user(
    State(pool): State<PgPool>,
    Path(id): Path<String>,
) -> Result<Json<User>, (StatusCode, String)> {
    let user = sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", id)
        .fetch_optional(&pool)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "User not found".to_string()))?;

    Ok(Json(user))
}

Testing

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validation() {
        let result = validate("[email protected]");
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_async_operation() {
        let result = fetch_data().await;
        assert!(result.is_ok());
    }
}

Tooling

# Format
cargo fmt

# Lint
cargo clippy -- -D warnings

# Test
cargo test

# Build release
cargo build --release

评论

支持 Markdown