Rust
190 bites tagged Rust — interview questions with model answers, and 60-second explainers.
Rust's `std::sync::Mutex`: Guarding Shared Data
A Rust `Mutex` guards shared data, granting access only via a temporary RAII "guard" that auto-releases the lock. It's used inside an `Arc` for safe multi-threaded mutation.
Rust Async Runtimes: The Engine for `async/await`
Rust's `async/await` is just syntax; an async runtime like Tokio is the engine that runs the code. It polls `Future`s until they complete, managing I/O and scheduling. This is essential for web servers.
Rust's async/await: Cooperative Concurrency
Rust's async/await is cooperative concurrency, where tasks explicitly yield control with `.await`. This is ideal for I/O-bound work like managing thousands of network connections. The biggest footgun: calling an `async` function without `.await` does nothing.
Rust Channels: Thread-Safe Communication
Rust channels are like a thread-safe conveyor belt for sending data between threads. Use them to pass work to workers or aggregate results. The footgun: the receiver blocks forever if any sender isn't dropped, as the channel only closes when all senders are…
Rust's std::thread::spawn: Create and Manage OS Threads
std::thread::spawn creates a new OS thread to run code concurrently, returning a JoinHandle to wait for completion. Use it for background tasks or parallel computations. The footgun: dropping the handle detaches the thread, risking resource leaks.
Rust Marker Traits: Properties as Types
Marker traits are empty labels telling the Rust compiler about a type's capabilities, like being copyable or thread-safe. They have no methods; their presence is the signal. They're key for concurrency (`Send`/`Sync`) and memory (`Copy`/`Sized`) safety checks.
Rust Associated Types: One Trait, One Concrete Type
Associated types link a placeholder type to a trait, ensuring any implementation provides one specific type. This cleans up code, like in Rust's `Iterator` trait. The footgun: a type can only implement a trait with an associated type once.
Rust's `impl Trait`: Hiding Concrete Types
Rust's `impl Trait` specifies a type by its behavior, not its name. Use it in function arguments for cleaner generics (`fn f(x: impl Debug)`) or in return types to hide complex types like closures and iterators, avoiding heap allocation.
Static Dispatch: Zero-Cost Abstraction via Monomorphization
Static dispatch resolves function calls at compile time, avoiding runtime overhead. Rust does this via monomorphization, creating specialized code for each concrete type. This is the default for generics, but the trade-off is larger binary sizes.
Composable Error Types with `thiserror` in Rust
`thiserror` generates boilerplate for custom Rust error types, letting you define specific, matchable errors for a library. Use it when callers need to handle different failure modes. The footgun is using it for simple app errors where `anyhow` would suffice.
Rust's `panic!`: When to Crash Your Program Intentionally
Rust's `panic!` is an emergency stop for unrecoverable bugs, intentionally crashing the current thread. It's for impossible states where continuing is dangerous, not for recoverable errors like failed I/O—use `Result` for that.
Result: Handling Recoverable Errors in Rust
Rust handles recoverable errors with the `Result<T, E>` enum, forcing you to deal with both success (`Ok`) and failure (`Err`) paths. This shows up when a function like `File::open` might fail.
Rust's Question Mark Operator (?): Propagate Errors, Not Boilerplate
The `?` operator cleans up Rust error handling by propagating `Err` values. Instead of a verbose `match` block, you append `?` to a `Result` or `Option`, and it automatically returns the error if present, letting you focus on the happy path.
Handling Errors with Rust's Result Enum
Rust's `Result` enum makes error handling explicit. Instead of returning a value that might be an error code, functions return either `Ok(value)` or `Err(error)`. It's used for recoverable failures like I/O.
Rust's Option<T>: Handling Absence Safely
Rust's Option<T> is a type-safe box that holds either a value (Some(T)) or nothing (None), eliminating null pointer errors. Use it for function returns that might fail or for optional struct fields. The footgun is `.unwrap()`, which panics on None.
Rust's NLL: Smarter Borrows Based on Use, Not Scope
Non-Lexical Lifetimes (NLL) make Rust's borrow checker smarter. A borrow's lifetime ends after its last use, not at the end of its code block. This allows modifying data after a borrow is finished, even if the reference variable is still in scope.
Rust's Interior Mutability: Mutating 'Immutable' Data
Interior mutability lets you modify data through an immutable reference, moving Rust's borrow checks from compile-time to runtime. It's used in single-threaded code when the compiler can't verify safe access.
GC vs. Ownership: Two Paths to Memory Safety
Rust's ownership model provides memory safety at compile-time, aiming for C++-level performance without a garbage collector. This makes it ideal for systems programming where resource control is key. The footgun is assuming all "safe" languages are equal.
Rust's Lifetime Elision: When You Can Skip 'a
Lifetime elision lets you omit explicit lifetimes (`'a`) in function signatures. The compiler infers them from common patterns, like a function taking one reference and returning one.
RAII in Rust: Automatic Cleanup via Scope
RAII ties a resource's lifetime to its owner's scope. When the owner variable is dropped, Rust automatically cleans up the resource, preventing leaks. This applies to heap memory, file handles, and locks. The footgun: cleanup is deterministic, not like a GC.
Rust's `Drop` Trait: Automatic Resource Cleanup
Rust's `Drop` trait provides automatic, deterministic cleanup, like a destructor. It's used to release external resources like file handles or network sockets when a value goes out of scope. The key footgun: you cannot implement `Drop` on a `Copy` type.
Rust's Copy Trait: Implicit Bitwise Duplication
Rust's `Copy` trait makes assignments duplicate a value instead of moving it, allowing the original to still be used. It's an implicit, bitwise copy for simple types like integers.
Rust Cargo Workspaces: A Monorepo Control Panel
A Cargo Workspace is a control panel for a multi-crate Rust project, unifying dependencies and build artifacts. Use it for related binaries and libraries to ensure consistent builds.
Rust's Module-to-Filesystem Mapping
Rust's module system maps directly to your file system. A `mod foo;` statement tells the compiler to look for `foo.rs` or `foo/mod.rs`. This is how you organize any multi-file Rust project.
Get Rust bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.