Rust
190 bites tagged Rust — interview questions with model answers, and 60-second explainers.
FFI Error Handling: Translation and Unwinding
FFI error handling is a translation layer: foreign errors must become Rust Results before safe code sees them, or you risk UB. You do this in -sys wrappers around C libraries. The footgun: foreign exceptions unwinding across boundary without -unwind ABI is UB.
TCP Listeners: Go vs Rust
Go spins up TCP listeners and handles connections with lightweight goroutines—1 million costs ~500MB—but GC pauses introduce 2-5ms latency. Rust trades boilerplate for zero-cost safety and consistent sub-100µs response times without garbage collection.
The Newtype Pattern: Type Safety for Primitives
Wrap a primitive type in a new struct to give it a unique, compile-time identity. A `Miles(f64)` is different from a `Kilometers(f64)`. Use it to prevent mixing up IDs or units. The footgun: you must explicitly implement or delegate methods for the new type.
Rust's Serde: Taming JSON with Types
Serde JSON translates between human-readable JSON text and native Rust structs, acting as a bilingual interpreter for your data. Use it for web APIs or config files.
Rust's TcpStream: Your Handle to a Network Connection
A `TcpStream` is Rust's handle to a network connection, closing automatically when it goes out of scope. Use it to talk to servers. The footgun: `connect()` can block forever; always prefer `connect_timeout()` in production to avoid hanging.
Rust Enums and Pattern Matching: Type-Safe Alternatives
Rust enums define a type that can be one of several variants, each holding its own data. They're used to model states like `Loading`/`Success`/`Error` or handle optional values with `Option<T>`.
Rust's Fearless Concurrency: Catch Bugs Before They Ship
Rust's "fearless concurrency" uses the ownership and type system to turn data races into compile-time errors. This allows you to safely use threads, message passing, or shared state without runtime surprises. The footgun is assuming this prevents all bugs.
Rust Lifetimes: Preventing Dangling References
Lifetimes are Rust's compile-time guarantee that a reference never outlives the data it points to. The borrow checker uses them to prevent dangling pointers, a common source of bugs.
Daemonizing Go/Rust Apps: Let the OS Do It
Daemonizing an app means running it as a background service, detached from your terminal. This is essential for web servers or job processors. The common footgun is writing custom daemon logic instead of using a system service manager like systemd.
The FromRequest Trait: Consuming Request Bodies in Axum
Axum's `FromRequest` trait defines how to create a type by consuming an HTTP request body. It's the core of extractors like `Json<T>` that deserialize POST data. The footgun: you can only use one `FromRequest` extractor per handler, as it consumes the body.
Rust's Tower Service: One Trait for Clients, Servers, and Middleware
Tower's Service trait is a universal API for async requests. It models any 'request -> future<response>' flow, unifying clients, servers, and middleware. Use it for HTTP servers or database clients. The footgun: ignoring `poll_ready` bypasses backpressure.
Terminal User Interfaces (TUIs): GUIs for the Console
A TUI is a graphical interface built from text, offering rich interactivity without leaving the console. Use them for system monitoring (btop), file management, or database clients. The footgun: don't confuse them with CLIs; TUIs are stateful apps.
Rust's Deref Trait: Smart Pointers Acting Like Data
The `Deref` trait lets a "smart pointer" type act like the data it contains, making wrappers transparent. It enables calling an inner type's methods directly on a wrapper, like using `&str` methods on a `String`. Its `deref()` method must never fail.
The Builder Pattern: Constructing Complex Objects in Rust
The Builder pattern lets you construct complex objects step-by-step using a chain of method calls. It's crucial in Rust for structs with many optional fields, since the language lacks default arguments.
Rust's `clap`: Build CLIs by Describing Them
`clap` lets you define a Rust struct representing your CLI's arguments, and it generates the parser, help text, and validation. It's used for building any Rust CLI, but its feature-richness can increase binary size over simpler alternatives.
cbindgen: Auto-generate C/C++ Headers for Rust
cbindgen automatically generates C/C++ headers for your Rust code, saving you from writing tedious FFI boilerplate. Use it when exposing a Rust library to other languages. Its feature set is ad-hoc, so it may not support your specific edge case out of the box.
Rust's `bindgen`: Auto-Generate FFI to C/C++
`bindgen` is a translator that reads C/C++ headers and writes the unsafe Rust FFI code to call them. It's used to integrate Rust with existing C libraries, like system APIs or legacy code, saving you from writing bindings by hand.
Rust: Expose Functions to C with `#[no_mangle]`
The `#[no_mangle]` attribute tells the Rust compiler not to alter a function's name, exposing a stable symbol for C code to call. Use it with `extern "C"` to create Rust libraries for other languages. The footgun is forgetting `extern "C"`, causing crashes.
Rust: Bridging C Strings with CStr and CString
CString and CStr are Rust's safe wrappers for C's nul-terminated strings. CString builds a C-compatible string to pass *out* of Rust; CStr interprets one coming *in*. Use them for any FFI calls.
Rust's `libc` Crate: Speaking the OS's Language
The `libc` crate is Rust's dictionary for C types, letting you talk to the OS. Use it for system calls or linking C libraries, like when building low-level network tools.
Rust's `extern` Block: Talking to Other Languages
An `extern` block is Rust's contract for calling code from other languages, like C. You declare external functions and statics, promising they exist. Use it for FFI to call system libraries, but know all calls are `unsafe` as Rust can't verify them.
Rust's Pin: Fixing a Value's Memory Address
Pin<P> tells the Rust compiler a value must not move from its memory location. Think of it as nailing an object to a specific spot on the memory shelf. This is crucial for self-referential types, like those in async runtimes.
Rust Const Generics: Parameterize by Value, Not Just Type
Const generics let Rust types be parameterized by values, not just other types. This allows writing code generic over array sizes, like `Matrix<T, const N: usize>`, ensuring dimensions are checked at compile time.
Rust Procedural Macros: Code That Writes Code
Procedural macros are compile-time functions that write Rust code for you. They power common patterns like Serde's `#[derive(Serialize)]`. The main footgun is hygiene: generated code can clash with local variables, so authors must use absolute paths to be…
Get Rust bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.