Debugging Refactor Snippets
Copy-paste before/after patterns for defects seen repeatedly in Rust code review and incidents.
Search across all documentation pages
Copy-paste before/after patterns for defects seen repeatedly in Rust code review and incidents.
Pick the scenario matching your compiler error or prod symptom; apply after variant; run tests.
// Before
let r = &data.items[0];
data.items.push(item);
use_ref(r);
// After
let snapshot = data.items[0].clone();
data.items.push(item);
use_val(snapshot);// Before
let cache = Rc<RefCell<Cache>>::new(...);
tokio::spawn(async move { cache.borrow_mut().fill().await });
// After
let cache = Arc::new(tokio::sync::Mutex::new(Cache::new()));
let c = cache.clone();
tokio::spawn(async move { c.lock().await.fill().await });// Before
async fn get(Path(id): Path<u64>) -> Json<User> {
Json(db.fetch(id).await.unwrap())
}
// After
async fn get(Path(id): Path<u64>) -> Result<Json<User>, ApiError> {
let user = db.fetch(id).await?.ok_or(ApiError::NotFound)?;
Ok(Json(user))
}// Before
std::fs::read_to_string(path)?
// After
tokio::task::spawn_blocking(move || std::fs::read_to_string(path)).await??// Before
let x = user_input as u8;
// After
let x = u8::try_from(user_input).map_err(|_| Error::OutOfRange)?;Keep team snippet library in internal wiki; link to these canonical fixes. Add test when applying snippet to prevent regression.
| Alternative | Use When | Don't Use When |
|---|---|---|
| rustfix/cargo fix | automated suggestions | semantic redesign |
| Mentor pairing | complex lifetimes | quick snippet ok |
PR to team playbook when same fix thrice.
Articles explain why; snippets are quick apply.
Fork internal section for company crates.
Require extra review; link SAFETY template.
Snippets assume axum 0.8 extractors; verify path if on 0.7.
Query macros need SQLX_OFFLINE data; separate snippet for CI.
Replace eager collect with lazy plan fix snippet in data team doc.
Add attribute snippet for external API DTOs.
cargo clippy --fix sometimes replaces snippet manually.
cargo test + clippy + relevant integration test.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 16, 2026