一键导入
rust-pitfalls
Rust Pitfalls -- Bugs That Compile guidance for Fortress Rollback. Use when Reviewing code, debugging common Rust mistakes, avoiding pitfalls.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Rust Pitfalls -- Bugs That Compile guidance for Fortress Rollback. Use when Reviewing code, debugging common Rust mistakes, avoiding pitfalls.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Crate Publishing guidance for Fortress Rollback. Use when Publishing to crates.io, version bumps, release checklist.
Changelog Practices guidance for Fortress Rollback. Use when Writing CHANGELOG entries, deciding what to document.
Design Decision Log Pattern guidance for Fortress Rollback. Use when Architectural decisions, design alternatives, superseding prior choices.
Repository-wide engineering policy and project context for Fortress Rollback. Use when implementing, diagnosing, reviewing, testing, documenting, or releasing changes in this repository.
GitHub Actions Best Practices guidance for Fortress Rollback. Use when Writing GitHub Actions workflows, CI debugging, actionlint, caching.
Workspace Organization guidance for Fortress Rollback. Use when Organizing workspace, splitting crates, module structure decisions.
| name | rust-pitfalls |
| description | Rust Pitfalls -- Bugs That Compile guidance for Fortress Rollback. Use when Reviewing code, debugging common Rust mistakes, avoiding pitfalls. |
aslet small: i8 = big as i8; // silently wraps!
// Use: i8::try_from(big).map_err(|_| Error::Overflow)?;
// OK when intentional: let low_byte: u8 = (value & 0xFF) as u8;
Clippy: cast_possible_truncation, cast_sign_loss, cast_possible_wrap
Use epsilon comparison or float-cmp/approx crate. Never assert_eq! on floats.
5 / 2 is 2, not 2.5. Be explicit: (5 + 1) / 2 for round-up.
&s[0..2] panics on multi-byte chars. Use s.chars().Path::join replaces base if argument is absolute. Validate relative paths.path.file_name().and_then(|n| n.to_str()) returns None if invalid.BTreeMap or sort keys.Vec::drain range panics if out of bounds. Clamp: v.drain(0..v.len().min(10)).collect::<Result<Vec<_>, _>> stops on first error but processes all items. Use explicit loop for short-circuit.let data = mutex.lock().map_err(|_| Error::MutexPoisoned)?;
Drop read lock before acquiring write lock. Re-check condition under write lock.
while !flag.load(Ordering::Acquire) {
#[cfg(loom)] loom::thread::yield_now();
#[cfg(not(loom))] std::hint::spin_loop();
}
In loom tests, use loom::sync::Arc, loom::thread, loom::sync::atomic::* -- not std::.
let cell = Arc::new(data);
let cell_for_thread = cell.clone(); // clone BEFORE spawn
thread::spawn(move || { cell_for_thread.do_work(); });
assert!(cell.is_ok()); // original still available
if let Fallthrough// BUG: e moved by if let, unusable in fallback
if let MyError::Specific { field } = e { return mapped; }
log::warn!("{:?}", e); // ERROR: moved!
// FIX: Use match
match e {
MyError::Specific { field } => OtherError::Mapped { field },
other => { log::warn!("{:?}", other); OtherError::Unknown }
}
.map_err().unwrap_or hides errors: Log or handle explicitly.? in Drop: Not allowed. Use if let Err(e) = self.cleanup() { /* log */ }.ok_or vs ok_or_elseUse ok_or_else(|| ...) when error construction allocates or is expensive. Use ok_or(...) for Copy error types (Clippy warns on unnecessary lazy evaluation).
pub type Result<T, E = MyError> shadows std::result::Result for glob importers. Use distinctive names: FortressResult.
#[serde(default)] on required fields: Silently accepts missing data.{"Active": null}. Use #[serde(rename_all = "snake_case")].#[track_caller] on async fn: Not supported by Rust. The attribute is silently ignored or triggers a clippy warning/error. Extract a sync helper that carries #[track_caller] and call it from the async fn, or remove the attribute entirely. A pre-commit grep hook catches this.#[should_panic] or catch_unwind.collect() then iterate: Chain iterators instead. Clippy: needless_collect.filter().map() with unwrap: Use filter_map instead.cloned() vs copied(): Use copied() for Copy types. Clippy: cloned_instead_of_copied.Vec::remove() in loop: O(n^2). Use retain() or swap_remove().clone() in hot loop: Borrow instead when possible.push() loop without capacity: Use Vec::with_capacity() or extend().Describe WHAT, not HOW -- unless performance guarantees are part of the API contract. Implementation details in comments become stale.
Proofs must verify what they claim. If name says "independent", actually test modification independence.
as casts that might truncatePath::join with potentially absolute pathsunwrap() on mutex locksunwrap_or_default() hiding errors? in Drop or some closuresdefault on required fieldsstd:: types in loom testsok_or vs ok_or_else for allocating errorsmatch not if let when fallback needs value#[track_caller] on async fn (not supported)