From rust
Rust内存管理规范 - 所有权转移、借用检查、生命周期标注、智能指针(Box/Rc/Arc/Cow)、零拷贝模式、内存泄漏排查。处理借用冲突、生命周期错误、内存优化、分配策略时加载。
npx claudepluginhub lazygophers/ccplugin --plugin rustThis skill uses the workspace's default tool permissions.
- **rust:dev** - 日常开发中的内存管理
Searches, retrieves, and installs Agent Skills from prompts.chat registry using MCP tools like search_skills and get_skill. Activates for finding skills, browsing catalogs, or extending Claude.
Searches prompts.chat for AI prompt templates by keyword or category, retrieves by ID with variable handling, and improves prompts via AI. Use for discovering or enhancing prompts.
Guides MCP server integration in Claude Code plugins via .mcp.json or plugin.json configs for stdio, SSE, HTTP types, enabling external services as tools.
&T(不可变借用)可以同时存在&mut T(可变借用)独占存在// 缩短借用作用域解决冲突
let mut map = HashMap::new();
let value = map.get("key").cloned(); // 借用在此结束
if value.is_none() {
map.insert("key", 42); // 现在可以可变借用
}
// 使用 entry API 避免两次查找
map.entry("key").or_insert(42);
// 函数参数优先借用
fn process(data: &[u8]) -> Result<Output> { /* ... */ } // 好
fn process(data: Vec<u8>) -> Result<Output> { /* ... */ } // 通常不必要
| 类型 | 用途 | 线程安全 | 开销 |
|---|---|---|---|
Box<T> | 堆分配、递归类型、trait 对象 | 由 T 决定 | 一次分配 |
Rc<T> | 单线程共享所有权 | 否 | 引用计数 |
Arc<T> | 多线程共享所有权 | 是 | 原子引用计数 |
Cow<'a, T> | 延迟克隆 | 由 T 决定 | 零或一次分配 |
// 单线程:RefCell(运行时借用检查)
use std::cell::RefCell;
let cell = RefCell::new(vec![1, 2, 3]);
cell.borrow_mut().push(4);
// 多线程:Mutex / RwLock
use std::sync::{Arc, RwLock};
let shared = Arc::new(RwLock::new(vec![1, 2, 3]));
shared.write().unwrap().push(4);
// 优先考虑:通道或原子类型替代锁
use std::sync::atomic::{AtomicU64, Ordering};
let counter = AtomicU64::new(0);
counter.fetch_add(1, Ordering::Relaxed);
// 省略规则覆盖大部分场景
fn first(s: &str) -> &str { &s[..1] }
// 需要标注时保持最小化
struct Parser<'input> {
input: &'input str,
pos: usize,
}
// 'static 仅在真正需要时使用
fn spawn_task(name: String) { // String 是 'static
tokio::spawn(async move {
println!("{name}");
});
}
// Cow:可能需要修改时延迟克隆
use std::borrow::Cow;
fn normalize_path(path: &str) -> Cow<'_, str> {
if path.contains("//") {
Cow::Owned(path.replace("//", "/"))
} else {
Cow::Borrowed(path)
}
}
// bytes crate:网络数据零拷贝
use bytes::{Bytes, BytesMut};
let data = Bytes::from_static(b"hello");
let slice = data.slice(0..3); // 无拷贝,引用计数
// &[u8] 切片:零拷贝视图
fn parse_header(data: &[u8]) -> Result<Header> {
let name = &data[..4]; // 无拷贝
// ...
}
// 使用 repr 控制布局
#[repr(C)] // C 兼容布局
#[repr(packed)] // 紧凑布局(慎用)
#[repr(align(64))] // 缓存行对齐
// 字段排序减少 padding
struct Optimized {
large: u64, // 8 bytes
medium: u32, // 4 bytes
small: u16, // 2 bytes
tiny: u8, // 1 byte
flag: bool, // 1 byte
} // 16 bytes(无 padding)
// SmallVec 避免小数组堆分配
use smallvec::SmallVec;
let tags: SmallVec<[String; 4]> = SmallVec::new();
// Arena 分配(大量同类型对象)
use bumpalo::Bump;
let arena = Bump::new();
let value = arena.alloc(42);
| AI 可能的解释 | 实际检查 |
|---|---|
| "clone 更简单" | ✅ 热路径中是否有不必要的克隆? |
| "用 String 参数方便" | ✅ 是否应为 &str 或 impl AsRef<str>? |
| "Arc<Mutex<T>> 是标准做法" | ✅ 是否可用 channel 或原子类型替代? |
| "Vec 够用" | ✅ 是否考虑 SmallVec 或固定数组? |
| "加个 'static 就行" | ✅ 是否真的需要 'static?能否缩短生命周期? |
| "Box<dyn Trait> 灵活" | ✅ 是否可用泛型实现静态分派? |
&str、&[T]、&Path).clone() 或 .to_string()Cow 处理可能需要修改的借用数据