Rust Async Patterns

作者 wshobson46891e7e60da無授權條款收錄於 2026年10月8日更新於 2026年10月8日

Master Rust async programming with Tokio, async traits, error handling, and concurrent patterns. Use when building async Rust applications, implementing concurrent systems, or debugging async code.

AI 產生的概覽

關於使用 Tokio 執行階段撰寫與偵錯非同步 Rust 程式的參考指南。

功能
此技能提供非同步 Rust 程式設計的正式環境模式,涵蓋非同步執行模型、Future、任務、執行階段、通道、串流、取消與錯誤處理。它提供快速開始的 Cargo 相依套件清單與範例程式碼,以及並行處理的注意事項。更詳細的範例放在隨附的參考文件中。
適用情境
適用於建置非同步 Rust 應用程式、實作並行網路服務、採用 Tokio 進行非同步 I/O,或偵錯與最佳化非同步程式碼的情境。也適合處理非同步錯誤或分析取消與任務管理問題時使用。
執行需求
不含指令碼,僅提供說明與一份參考文件。範例假定已安裝 Rust 工具鏈與 Cargo,並使用 tokio、futures、async-trait、anyhow、tracing、tracing-subscriber 等 crate。

Rust Async Patterns

Production patterns for async Rust programming with Tokio runtime, including tasks, channels, streams, and error handling.

When to Use This Skill

  • Building async Rust applications
  • Implementing concurrent network services
  • Using Tokio for async I/O
  • Handling async errors properly
  • Debugging async code issues
  • Optimizing async performance

Core Concepts

1. Async Execution Model

Future (lazy) → poll() → Ready(value) | Pending                ↑           ↓              Waker ← Runtime schedules

2. Key Abstractions

ConceptPurpose
FutureLazy computation that may complete later
async fnFunction returning impl Future
awaitSuspend until future completes
TaskSpawned future running concurrently
RuntimeExecutor that polls futures

Quick Start

toml
# Cargo.toml[dependencies]tokio = { version = "1", features = ["full"] }futures = "0.3"async-trait = "0.1"anyhow = "1.0"tracing = "0.1"tracing-subscriber = "0.3"
rust
use tokio::time::{sleep, Duration};use anyhow::Result;
#[tokio::main]async fn main() -> Result<()> {    // Initialize tracing    tracing_subscriber::fmt::init();
    // Async operations    let result = fetch_data("https://api.example.com").await?;    println!("Got: {}", result);
    Ok(())}
async fn fetch_data(url: &str) -> Result<String> {    // Simulated async operation    sleep(Duration::from_millis(100)).await;    Ok(format!("Data from {}", url))}

Detailed patterns and worked examples

Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

Best Practices

Do's

  • Use tokio::select! - For racing futures
  • Prefer channels - Over shared state when possible
  • Use JoinSet - For managing multiple tasks
  • Instrument with tracing - For debugging async code
  • Handle cancellation - Check CancellationToken

Don'ts

  • Don't block - Never use std::thread::sleep in async
  • Don't hold locks across awaits - Causes deadlocks
  • Don't spawn unboundedly - Use semaphores for limits
  • Don't ignore errors - Propagate with ? or log
  • Don't forget Send bounds - For spawned futures

來源與署名

來源:wshobson/agents位於plugins/systems-programming/skills/rust-async-patterns提交46891e7

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架