Files
atelier/languages/rust.md
T
Jon Chery 4e433158cd docs(P03): complete language-derived extension — v0.4
---ci---
project: atelier
phase: 3
milestone: v0.4
status: complete
phase_role: execution
phase_tag: v0.3.3
requirements:
  covered: [ATELIER-102, ATELIER-103, ATELIER-104, ATELIER-105]
  partial: []
---/ci---
2026-08-05 16:07:21 +00:00

86 lines
3.4 KiB
Markdown

# Rust — Language Application
> How Atelier's domain principles apply in Rust specifically. Derives from `domains/` docs.
## Derived Docs
- [rs-ownership.md](rs-ownership.md) — Send/Sync, lifetimes, borrowing, ownership transfer.
- [rs-tooling.md](rs-tooling.md) — cargo, clippy, fmt, edition discipline.
- [rs-async.md](rs-async.md) — tokio, async traits, cancellation, pin.
- [rs-testing.md](rs-testing.md) — #[test], proptest, property testing, mock discipline.
## Type System (C1 Correctness, Data P7 Type Fidelity)
- **Newtypes for domain concepts:** `struct UserId(String);` — zero-cost, type-safe.
- **`enum` for finite domains:** `enum Status { Pending, Paid, Shipped }` — exhaustive.
- **No `unsafe` without justification and review:** `unsafe` opts out of the compiler's guarantees.
```rust
struct UserId(String);
struct OrderId(String);
// Cannot pass OrderId where UserId is expected
fn get_user(id: UserId) -> Result<User, Error> { ... }
```
## Error Handling (Errors P1 Errors are Data)
- **`Result<T, E>` for fallible operations:** errors are values, not exceptions.
- **`thiserror` for error enums, `anyhow` for applications:**
```rust
#[derive(thiserror::Error)]
enum AppError {
#[error("not found: {0}")]
NotFound(String),
#[error("validation: {0}")]
Validation(String),
#[error(transparent)]
Io(#[from] std::io::Error),
}
```
- **`?` for propagation, not `unwrap()`:** `unwrap()` panics in production.
- **No `panic::catch_unwind` for control flow:** panics are for bugs, not errors.
## Concurrency (Concurrency — Rust's ownership model)
- **`Send` and `Sync` traits enforced by the compiler:** data races are compile errors.
- **`Arc<T>` for shared, `Mutex<T>`/`RwLock<T>` for mutation:** the lock is explicit.
- **`tokio` for async:** `async fn`, `.await`. Bounded channels (`tokio::sync::mpsc::channel(N)`).
- **`Drop` for cleanup:** no leaked resources (no `defer` needed; RAII).
```rust
async fn fetch_with_timeout(url: &str) -> Result<Response, Error> {
tokio::time::timeout(Duration::from_secs(5), fetch(url)).await??;
}
```
## Immutability (Concurrency P1 Immutability by Default)
- **Variables are immutable by default:** `let x = 5;` not `let mut x = 5;`.
- **`&T` (shared ref) over `&mut T` (exclusive ref):** the compiler enforces aliasing rules.
- **Interior mutability (`Cell`/`RefCell`) only when needed:** not as a default.
## Nullability (C1)
- **`Option<T>`, not nullable pointers:** `Some(x)` / `None`. The compiler enforces handling.
- **No `null`:** Rust has no null. `Option::None` is the explicit absence.
- **`?` on `Option` for propagation:** `fn get_name(user: User) -> Option<String> { user.profile?.name }`.
## Testing (Testing)
- **`#[test]` + `#[cfg(test)] mod tests`:** tests co-located.
- **`proptest` or `quickcheck` for property-based tests:** edge case coverage (P9).
- **`tokio::test` for async tests.**
- **No `SystemTime::now()` in tests:** inject an `Instant` or a mock clock.
## Observability (Observability P1)
- **`tracing` crate:** structured logs + spans + traces. Not `println!`.
- **`tracing::instrument` on functions:** automatic span context.
- **`tracing-subscriber` with JSON format:** structured output for production.
## Tooling (DevOps P2)
- **`cargo clippy`:** lint. `cargo clippy -- -D warnings` in CI.
- **`cargo fmt`:** format.
- **`cargo test`:** tests. `cargo test --release` for perf-sensitive.
- **Committed `Cargo.lock`:** reproducible builds (even for libraries, for CI).