- Never use
panic!,unwrap(), orexpect()in production code. - Always handle errors explicitly using
ResultorOption.
- Run with strict pedantic linting enabled.
- Follow all clippy suggestions without adding
#[allow]directives. - Project-specific strictness is configured in
clippy.tomlorCargo.toml.
- Format all code:
cargo fmt --all - Sort imports:
cargo sort --grouped
- Use the latest minor version for all dependencies.
- GOOD:
version = "1.0" - BAD:
version = "1"orversion = "1.0.123"
- Prefer
core::overstd::when possible. - Prefer
crate::oversuper::for project modules.
- All imports must be at the top of the file, before any code.
- Use long paths in imports, short paths in code:
- GOOD:
use std::collections::HashMap;andlet m = HashMap::new(); - BAD:
let m = std::collections::HashMap::new();
- GOOD:
- More relaxed for function calls:
let a = std::thread::spawn();is acceptable.
- Use idiomatic traits for conversions:
Fromfor infallible conversions.TryFromfor fallible conversions.
- Avoid creating custom conversion functions when traits would be more appropriate.
When type names conflict, use use aliases following this priority order:
std(highest priority)- Third-party crates
- Project crates (lowest priority)
use somecrate::HashMap as NewHashMap;- Prefer references (
&T,&mut T) over passing values by default. - Minimize cloning; prefer borrowing or
Cow<'a, T>for copy-on-write semantics. - Ergonomic over performance if the trade-off is not worth the complexity:
- GOOD: Use
StringwhenCow<'a, str>would require awkward code. - GOOD: Use
Cow<'a, str>when you can pay the ergonomics cost for zero-copy.
- GOOD: Use
Organize Rust source files in this order:
- const - associated constants
- Type definitions - structs, enums, unions, type aliases
- impl std traits - Display, Debug, Clone, Copy, etc.
- impl 3rd party crate traits - traits from dependencies
- impl project traits - traits defined in this project
- impl blocks - custom methods for the type
- functions - free/public helper functions
- tests -
#[cfg(test)]module with unit tests
// 1. const
impl MyType {
pub const MAX_VALUE: i32 = 100;
}
// 2. Type definition
pub struct MyType {
field: i32,
}
// 3. impl std traits
use std::fmt::{Display, Formatter, Result};
impl Display for MyType {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(f, "{}", self.field)
}
}
// 4. impl 3rd party trait
use SomeCrate::Serializable;
impl Serializable for MyType { ... }
// 5. impl project trait
use crate::traits::Validatable;
impl Validatable for MyType { ... }
// 6. impl blocks (custom methods)
impl MyType {
pub fn new() -> Self { Self { field: 0 } }
}
// 7. functions
pub fn helper_function() { ... }
// 8. tests
#[cfg(test)]
mod tests {
use crate::MyType;
#[test]
fn test_something() { ... }
}