Skip to main content 首页 创作者 inugamidev ultrathink-oss rust
rust Rust ownership model, async programming with Tokio, web frameworks (Axum/Actix), error handling, and systems programming patterns
跳到安装 Skills Marketplace 发现并探索由社区构建的 Agent Skills
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/InugamiDev/ultrathink-oss --skill rust命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
下载 Zip 下载中... 同仓库更多 Skills Unified design foundations — design system architecture, tokens, component specs, visual principles, creative vision, figma integration, plus brand design system loader (66 real brands via DESIGN.md). Absorbs design, design-system, design-systems, design-principles, design-router, creative-vision, figma, design-md.
Render, summarize, and present markdown documents and structured content in multiple output modes
Ultra UI skill - combines Google's DESIGN.md spec (machine-readable design tokens) with the ui-ux-pro-max knowledge base (91 styles, 161 palettes, 73 font pairings, 161 products, 104 UX guidelines, 25 chart types). Generates lint-clean DESIGN.md files, validates token references and WCAG contrast, exports Tailwind/DTCG tokens, and diffs design systems version-over-version.
name rust description Rust ownership model, async programming with Tokio, web frameworks (Axum/Actix), error handling, and systems programming patterns layer domain category backend triggers ["rust","cargo","tokio","axum","actix","ownership","borrow checker","rust web"] inputs ["Rust application requirements","Performance-critical system needs","Web service specifications"] outputs ["Idiomatic Rust implementations","Async patterns with Tokio","Web framework configurations"] linksTo ["microservices","postgresql","redis","websockets","message-queues"] linkedFrom ["error-handling","testing"] preferredNextSkills ["postgresql","redis","microservices"] fallbackSkills ["golang","nodejs"] riskLevel low memoryReadPolicy selective memoryWritePolicy none sideEffects []
Rust Domain Skill
Purpose
Provide expert-level guidance on Rust development, including the ownership system, async programming with Tokio, web framework patterns (Axum, Actix), error handling with thiserror/anyhow, and production-grade systems programming.
Key Patterns
1. Ownership and Borrowing
fn process_name (name: &str ) -> String {
name.to_uppercase ()
}
struct Config <'a > {
database_url: &'a str ,
app_name: &'a str ,
}
impl <'a > Config<'a > {
fn connection_string (&self ) -> String {
format! ("{}?app={}" , self .database_url, self .app_name)
}
}
use std::sync::{Arc, RwLock};
#[derive(Clone)]
struct AppState {
cache: Arc<RwLock<HashMap<String , CachedItem>>>,
db: Arc<Pool<Postgres>>,
}
impl {
(& , key: & ) <CachedItem> {
.cache. (). (). (key). ()
}
(& , key: , item: CachedItem) {
.cache. (). (). (key, item);
}
}
AppState
fn
get_cached
self
str
->
Option
self
read
unwrap
get
cloned
fn
set_cached
self
String
self
write
unwrap
insert
2. Error Handling use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("resource not found: {resource} with id {id}" )]
NotFound { resource: String , id: String },
#[error("unauthorized: {0}" )]
Unauthorized (String ),
#[error("validation failed: {0}" )]
Validation (String ),
#[error("database error" )]
Database (#[from] sqlx::Error),
#[error("external service error" )]
ExternalService (#[from] reqwest::Error),
#[error(transparent)]
Internal (#[from] anyhow::Error),
}
impl IntoResponse for AppError {
fn into_response (self ) -> Response {
let (status, code, message) = match &self {
AppError::NotFound { .. } => (StatusCode::NOT_FOUND, "NOT_FOUND" , self .to_string ()),
AppError::Unauthorized (msg) => (StatusCode::UNAUTHORIZED, "UNAUTHORIZED" , msg.clone ()),
AppError::Validation (msg) => (StatusCode::UNPROCESSABLE_ENTITY, "VALIDATION" , msg.clone ()),
AppError::Database (_) => {
tracing::error!(error = ?self , "database error" );
(StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL" , "internal error" .into ())
}
AppError::ExternalService (_) => {
tracing::error!(error = ?self , "external service error" );
(StatusCode::BAD_GATEWAY, "BAD_GATEWAY" , "upstream error" .into ())
}
AppError::Internal (_) => {
tracing::error!(error = ?self , "internal error" );
(StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL" , "internal error" .into ())
}
};
(status, Json (json!({ "error" : { "code" : code, "message" : message } }))).into_response ()
}
}
type AppResult <T> = Result <T, AppError>;
3. Axum Web Framework use axum::{
extract::{Path, Query, State, Json},
http::StatusCode,
middleware,
routing::{get, post, delete},
Router,
};
use tower::ServiceBuilder;
use tower_http::{
cors::CorsLayer,
trace::TraceLayer,
compression::CompressionLayer,
timeout::TimeoutLayer,
};
pub fn create_router (state: AppState) -> Router {
let api = Router::new ()
.route ("/users" , get (list_users).post (create_user))
.route ("/users/{id}" , get (get_user).delete (delete_user))
.layer (middleware::from_fn_with_state (state.clone (), auth_middleware));
Router::new ()
.nest ("/api/v1" , api)
.route ("/health" , get (health_check))
.layer (
ServiceBuilder::new ()
.layer (TraceLayer::new_for_http ())
.layer (CompressionLayer::new ())
.layer (TimeoutLayer::new (Duration::from_secs (30 )))
.layer (CorsLayer::permissive ()),
)
.with_state (state)
}
async fn list_users (
State (state): State<AppState>,
Query (params): Query<ListUsersParams>,
) -> AppResult<Json<PaginatedResponse<UserResponse>>> {
let users = state.user_service.list (params.into ()).await ?;
Ok (Json (users))
}
async fn create_user (
State (state): State<AppState>,
Json (body): Json<CreateUserRequest>,
) -> AppResult<(StatusCode, Json<UserResponse>)> {
let user = state.user_service.create (body).await ?;
Ok ((StatusCode::CREATED, Json (user)))
}
async fn auth_middleware (
State (state): State<AppState>,
mut req: Request,
next: Next,
) -> Result <Response, AppError> {
let token = req
.headers ()
.get ("Authorization" )
.and_then (|h| h.to_str ().ok ())
.and_then (|h| h.strip_prefix ("Bearer " ))
.ok_or_else (|| AppError::Unauthorized ("missing token" .into ()))?;
let claims = state.auth_service.verify (token).await ?;
req.extensions_mut ().insert (claims);
Ok (next.run (req).await )
}
4. Async with Tokio use tokio::sync::{mpsc, Semaphore};
use tokio::time::{timeout, Duration};
async fn process_events (mut rx: mpsc::Receiver<Event>) {
while let Some (event) = rx.recv ().await {
if let Err (e) = handle_event (&event).await {
tracing::error!(error = ?e, event = ?event, "failed to handle event" );
}
}
}
async fn fetch_all (urls: Vec <String >, max_concurrent: usize ) -> Vec <Result <String , reqwest::Error>> {
let semaphore = Arc::new (Semaphore::new (max_concurrent));
let client = reqwest::Client::new ();
let tasks : Vec <_> = urls
.into_iter ()
.map (|url| {
let sem = semaphore.clone ();
let client = client.clone ();
tokio::spawn (async move {
let _permit = sem.acquire ().await .unwrap ();
client.get (&url).send ().await ?.text ().await
})
})
.collect ();
let mut results = Vec ::with_capacity (tasks.len ());
for task in tasks {
results.push (task.await .unwrap ());
}
results
}
async fn run_server (listener: TcpListener, app: Router) {
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn (async move {
let mut sigterm = tokio::signal::unix::signal (SignalKind::terminate ()).unwrap ();
tokio::select! {
_ = tokio::signal::ctrl_c () => {}
_ = sigterm.recv () => {}
}
let _ = shutdown_tx.send (());
});
axum::serve (listener, app)
.with_graceful_shutdown (async { shutdown_rx.await .ok (); })
.await
.unwrap ();
}
5. Database with SQLx use sqlx::{PgPool, FromRow, query_as};
#[derive(FromRow)]
struct User {
id: Uuid,
email: String ,
name: String ,
created_at: chrono::DateTime<chrono::Utc>,
}
async fn get_user (pool: &PgPool, id: Uuid) -> AppResult<User> {
sqlx::query_as!(
User,
r#"SELECT id, email, name, created_at FROM users WHERE id = $1"# ,
id
)
.fetch_optional (pool)
.await ?
.ok_or_else (|| AppError::NotFound {
resource: "user" .into (),
id: id.to_string (),
})
}
async fn transfer_credits (pool: &PgPool, from: Uuid, to: Uuid, amount: i64 ) -> AppResult<()> {
let mut tx = pool.begin ().await ?;
sqlx::query!("UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1" , amount, from)
.execute (&mut *tx)
.await ?;
sqlx::query!("UPDATE accounts SET balance = balance + $1 WHERE id = $2" , amount, to)
.execute (&mut *tx)
.await ?;
tx.commit ().await ?;
Ok (())
}
Best Practices
Use clippy with #![deny(clippy::all)] in CI
Prefer &str over String in function parameters
Use thiserror for library errors, anyhow for application errors
Use tracing instead of log for structured, async-aware logging
Prefer Arc<T> over Rc<T> unless single-threaded is guaranteed
Use tokio::spawn for CPU-bound work in spawn_blocking
Prefer iterators over manual loops -- they often optimize better
Use #[derive] macros extensively: Debug, Clone, PartialEq, Serialize, Deserialize
Test with #[tokio::test] for async tests
Use cargo deny to audit dependencies for vulnerabilities
Common Pitfalls Pitfall Impact Fix Holding MutexGuard across .await Deadlock Scope the lock, clone data out unwrap() in production codePanics Use ? operator, expect() with context Cloning everything to satisfy borrow checker Performance degradation Restructure code, use Arc, references Blocking the Tokio runtime Async task starvation Use tokio::task::spawn_blocking Not setting #[tokio::main(flavor = "multi_thread")] Single-threaded runtime Explicitly configure runtime Unbounded channels Memory exhaustion Use mpsc::channel(capacity)