rust
Skill này làm gì
Hướng dẫn này cung cấp các thực hành tốt nhất để viết code Rust hiệu quả và đúng chuẩn. Nó dạy cách dùng đúng các tính năng như “ownership” và “borrowing”, xử lý lỗi chắc chắn và dùng hiệu quả iterator và pattern matching.
Khi nào nên dùng
- ✓Khi học các khái niệm nền tảng của Rust.
- ✓Khi tái cấu trúc code Rust có sẵn để hiệu quả hơn.
- ✓Khi gỡ lỗi các lỗi thường gặp trong Rust.
Liên kết skill
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/rust/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Làm sao để tránh sao chép dữ liệu không cần thiết trong Rust?”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
AI so sánh các ví dụ code Rust “xấu” với “tốt”. Nó giải thích nguyên tắc đằng sau các thực hành tốt nhất, như ưu tiên tham chiếu (`&str`) thay vì bản sao (`String`) và dùng toán tử `?` để xử lý lỗi.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
Rust: Idiomatic Efficiency Reference
When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for rust.
Table of Contents
- Ownership & Borrowing
- Error Handling
- Iterators
- Pattern Matching
- Structs & Enums
- Concurrency
- Anti-patterns specific to Rust
1. Ownership & Borrowing {#ownership}
// ❌ Cloning to avoid thinking about lifetimes
fn get_name(user: &User) -> String {
user.name.clone()
}
// ✅ — return a reference when the data lives long enough
fn get_name(user: &User) -> &str {
&user.name
}
// ❌ Taking ownership when borrowing suffices
fn print_name(name: String) {
println!("{name}");
}
// ✅
fn print_name(name: &str) {
println!("{name}");
}
// ❌ Unnecessary .to_string() / .to_owned() in hot paths
let key = id.to_string();
map.get(&key)
// ✅ — use Borrow trait; HashMap<String, V> accepts &str as key
map.get(id)
Prefer &str over String in function parameters unless the function needs to own the data.
2. Error Handling {#errors}
// ❌ .unwrap() in production code
let file = File::open(path).unwrap();
// ✅
let file = File::open(path)
.map_err(|e| AppError::Io { path: path.to_owned(), source: e })?;
// ❌ Manual match on Result for every call
match do_thing() {
Ok(v) => v,
Err(e) => return Err(e),
}
// ✅ — the ? operator
let v = do_thing()?;
// ❌ Box<dyn Error> everywhere (loses type info)
fn run() -> Result<(), Box<dyn std::error::Error>> { ... }
// ✅ — use thiserror for library errors, anyhow for application errors
use anyhow::{Context, Result};
fn run() -> Result<()> {
do_thing().context("failed during run")?;
Ok(())
}
// ❌ Separate error enum variant for every call site
enum Error { FileOpen, FileRead, Parse, Network, ... }
// ✅ — use thiserror with #[from] for automatic conversion
#[derive(thiserror::Error, Debug)]
enum Error {
#[error("io error")] Io(#[from] std::io::Error),
#[error("parse error")] Parse(#[from] serde_json::Error),
}
3. Iterators {#iterators}
// ❌ Imperative accumulation
let mut result = Vec::new();
for item in &items {
if item.active {
result.push(item.name.to_uppercase());
}
}
// ✅
let result: Vec<_> = items.iter()
.filter(|i| i.active)
.map(|i| i.name.to_uppercase())
.collect();
// ❌ Manual sum
let mut total = 0;
for order in &orders { total += order.amount; }
// ✅
let total: u64 = orders.iter().map(|o| o.amount).sum();
// ❌ Index-based loop
for i in 0..items.len() {
process(&items[i]);
}
// ✅
for item in &items {
process(item);
}
// With index:
for (i, item) in items.iter().enumerate() {
process(i, item);
}
Chain iterators lazily; only .collect() when you actually need a concrete collection.
4. Pattern Matching {#patterns}
// ❌ if-let chain that should be match
if let Some(x) = opt {
if x > 0 {
use(x)
}
}
// ✅
if let Some(x) = opt.filter(|&x| x > 0) {
use(x)
}
// or match with guard:
match opt {
Some(x) if x > 0 => use(x),
_ => {}
}
// ❌ match with identical arms
match status {
Status::Active => true,
Status::Pending => true,
Status::Inactive => false,
}
// ✅
matches!(status, Status::Active | Status::Pending)
// ❌ Destructuring in body instead of pattern
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(c) => { let r = c.radius; r * r * PI }
Shape::Rect(r) => { let w = r.width; let h = r.height; w * h }
}
}
// ✅ — destructure in pattern
match shape {
Shape::Circle(Circle { radius, .. }) => radius * radius * PI,
Shape::Rect(Rect { width, height }) => width * height,
}
5. Structs & Enums {#structs}
// ❌ Enum variant carrying bool for binary state
enum State { Running(bool) } // true = paused?
// ✅ — explicit variants
enum State { Running, Paused, Stopped }
// ❌ Struct with many Option fields (stringly optional)
struct Config {
timeout: Option<u64>,
retries: Option<u32>,
base_url: Option<String>,
}
// ✅ — use Default + builder pattern or #[derive(Default)] with sensible defaults
#[derive(Default)]
struct Config {
timeout: u64, // default 0 = no timeout
…
Câu hỏi thường gặp
“Ownership” và “borrowing” là gì?
“Ownership” là cách Rust quản lý bộ nhớ: mỗi giá trị có một chủ sở hữu. “Borrowing” cho phép bạn tạm thời cho mượn quyền truy cập một giá trị mà không chuyển quyền sở hữu.
Vì sao nên tránh `.unwrap()`?
`.unwrap()` có thể làm chương trình bị crash bất ngờ nếu giá trị không như mong đợi. Tốt hơn là dùng toán tử `?` hoặc `match` để xử lý lỗi an toàn.
Iterator trong Rust là gì?
Iterator là cách hiệu quả để xử lý tập hợp dữ liệu, cho phép bạn nối các thao tác như lọc và ánh xạ các phần tử trước khi thu thập kết quả cuối cùng.
Chi tiết
Mô tả gốc của tác giả
Language-specific super-code guidelines for rust.
Độ phổ biến
- Sao GitHub
- 48k
- Vị trí xếp hạng
- #5898
- Giấy phép
- MIT
- Cập nhật
- 15/10/2026
Bình luận
- …
Thêm skill từ kho mã này
00-andruia-consultant
48kGiúp agent của bạn bắt đầu hoặc cải thiện các dự án AI. Phân tích mã, gợi ý công cụ và lập kế hoạch hành động bằng tiếng Tây Ban Nha.
007
48kCho phép agent của bạn thực hiện kiểm toán bảo mật và mô hình hóa mối đe dọa. Hữu ích để bảo vệ dự án khỏi các cuộc tấn công và lỗ hổng.
10-andruia-skill-smith
48kGiúp agent của bạn tạo hoặc cải thiện các công cụ AI. Xác định cách công cụ hoạt động, viết tài liệu và kiểm tra cấu trúc.
20-andruia-niche-intelligence
48kGiúp agent của bạn tạo bản tóm tắt về một ngành cụ thể. Hữu ích để hiểu bối cảnh, quy tắc, cách người dùng tương tác và rủi ro của dự án.
Skill tương tự
diffs
394kGiúp agent của bạn tạo một diff có thể chia sẻ về các chỉnh sửa, dưới dạng liên kết xem hoặc file ảnh, thay vì một bản tóm tắt viết tay.
coding-agent
394kGiúp agent của bạn giao một việc lập trình lớn cho Codex, Claude Code hoặc OpenCode chạy nền, rồi theo dõi tiến độ của nó.
gh-issues
394kGiúp agent của bạn tìm issue trên GitHub, chọn những issue cần xử lý và mở pull request với bản sửa, kể cả theo dõi nhận xét đánh giá.