Rust Professional Development
Goal: Write idiomatic, high-performance, and memory-safe Rust code following standard community practices (The Rust Way).
1. Core Principles
- •Ownership & Borrowing: strictly enforce ownership rules. Avoid
.clone()unless necessary. UseArc<Mutex<T>>orRwLock<T>for shared state only when message passing (mpsc) is not viable. - •Error Handling: Use
Result<T, E>withthiserrorfor libraries andanyhowfor applications. Never use.unwrap()in production code; use.expect()with a context message or?operator. - •Async Runtime: Default to
tokiofor general purpose apps. Usejoin_allfor parallel execution of futures. - •Type System: Leverage traits and generics for zero-cost abstractions. Use
New Typepattern to enforce validation at compile time.
2. Toolchain & Ecosystem
- •Build System:
cargo - •Linter:
clippy(Treat warnings as errors in CI) - •Formatter:
rustfmt - •Testing: Built-in
#[test]andcargo test. Usemockallfor mocking traits.
3. Recommended Project Structure
text
my_crate/
├── Cargo.toml
├── src/
│ ├── main.rs # Binary entry point
│ ├── lib.rs # Library entry point
│ ├── bin/ # Additional binaries
│ ├── models/ # Data structures
│ ├── error.rs # Central error definition
│ └── utils.rs # Helper functions
└── tests/ # Integration tests
└── integration_test.rs
4. Common Dependencies (The Standard Stack)
- •Async:
tokio,futures - •Web:
axumoractix-web - •Serialization:
serde,serde_json - •Error Handling:
anyhow,thiserror - •Tracing/Logging:
tracing,tracing-subscriber - •config:
configcrate for environment management
5. Security & Performance
- •Memory: Use
Stringonly when ownership is needed; prefer&strfor function arguments. - •Unsafe: Avoid
unsafeblocks unless absolutely necessary and documented with// SAFETY:comment explaining why it holds. - •Vectors: Pre-allocate vectors with
Vec::with_capacity(n)if size is known.
6. Implementation Workflow
- •Define Types: Start with
structandenumdefinitions. - •Define Traits: Outline behavior using traits.
- •Implement Logic: Implement traits for types.
- •Wire up: Connect components in
main.rsorlib.rs. - •Test: Write unit tests alongside code and integration tests in
tests/.
Anti-Patterns to Avoid:
- •Excessive use of
Box<dyn Trait>(prefer generics with static dispatch). - •Ignoring
Result(always handle or propagate). - •Global mutable state (use dependency injection or actor pattern).