Rust Core: Idiomatic Patterns & Philosophy
Core Philosophy
- Safety First:
unsafeis forbidden unless the user explicitly requests it and provides a rationale. Even then, you must wrap it in a// SAFETY:comment. - Expression-Oriented: Rust is an expression language. Use this.
- Bad:
let mut x = 0; if condition { x = 1; } else { x = 2; } - Good:
let x = if condition { 1 } else { 2 };
- Bad:
- Type-Driven Design: Make invalid states unrepresentable. Use
enums to encode state machines.
Idiomatic Patterns
Error Handling
- Libraries: Use
thiserror. - Applications: Use
anyhow::Result.
Iterators vs Loops
- Prefer
Iteratorcombinators for transformation and filtering. - Bad:
- Good:
Option & Result Combinators
- Use
map,and_then,unwrap_or_else. - Avoid excessive
if let Some(x) = ynesting. - Better:let value = y.ok_or(MyError::Missing)?.process();
Project Strictness
- Async/Await: Use
tokioas the default runtime. - Formatting: Strictly adhere to
rustfmt. Code must passcargo fmt --check. - Modules: Keep
main.rssmall. Move logic tolib.rsor submodules (src/my_module/mod.rsorsrc/my_module.rs). - Visibility: All fields in structs are private by default. Use
pub(crate)for internal sharing,pubonly for API surface.