Rust topics
- Result and the ? operator in Rust: How Rust handles errors with Result<T, E>: Ok and Err, match, the ? operator for early returns, main returning Result, and map_err.
- Option vs Result in Rust: which one should you return?: When to return Option<T> and when to return Result<T, E> in Rust, how to convert between them with ok_or and ok(), and using ? with each.
- Custom error types in Rust: enums, Display and From: How to write your own error type in Rust: an error enum, impl Display and std::error::Error, From conversions for ?, and the thiserror shortcut.
- Generics in Rust: generic functions, structs and trait bounds: How to write generic functions and structs in Rust, add trait bounds like T: PartialOrd, use where clauses, and why generics cost nothing at run time.
- Traits in Rust: defining shared behavior: How Rust traits work: defining a trait, implementing it for your types, default methods, trait bounds, impl Trait, and deriving standard traits.
- Trait objects vs generics in Rust: dyn Trait vs impl Trait: When to use generics (impl Trait, static dispatch) and when to use trait objects (dyn Trait, Box<dyn Trait>, dynamic dispatch) in Rust.
- Rust lifetimes explained: What lifetimes are in Rust, why the borrow checker needs them, how to read and write 'a annotations, the elision rules, and structs that hold references.
- The 'static lifetime in Rust (&'static str and T: 'static): What 'static really means in Rust: &'static references vs T: 'static bounds, why thread::spawn needs 'static, and why String is 'static.
- From and Into in Rust: converting between types: How From and Into work in Rust: implementing From for your types, calling .into(), TryFrom for fallible conversions, and From for ? errors.
- Display vs Debug in Rust ({} vs {:?}): The difference between Display and Debug in Rust, when to derive Debug, how to implement Display for your own types, and the E0277 errors.
- Rust error E0277: the trait bound is not satisfied: What Rust's E0277 error means (a type doesn't implement a required trait) and how to fix its most common forms: Display, Ord, Send, ? and collect.
- Hello World in Rust: fn main, println! and Cargo: Write and run your first Rust program with Cargo, and learn what fn main, println! and the exclamation mark mean.
- Variables and mutability in Rust (let vs let mut): Why Rust variables are immutable by default, when to use let mut, const vs let, type inference, and the E0384 error explained.
- Shadowing in Rust: reusing a variable name with let: What shadowing is in Rust, how let x = x + 1 differs from mut, changing a value's type under the same name, and shadowing in inner blocks.
- Rust integer types and integer overflow: i8 to i128, u8 to usize: Rust integer ranges, what happens on overflow in debug and release builds, and checked, wrapping and saturating math.
- Converting between number types in Rust (as, From and TryFrom): How to convert i32 to f64, u64 to usize and back in Rust with as, From and TryFrom, and the truncation and wrapping traps of as.
- Rust println! formatting: {}, {:?}, width and precision: A cheat sheet for Rust format strings: placeholders, inline {name} args, {:?}, {:.2}, padding and alignment, hex, binary and format!.
- String vs &str in Rust: what's the difference?: Rust's two string types explained: owned, growable String vs borrowed &str slices, when to use each, and how to convert between them.
- Reading user input in Rust (stdin, read_line and parse): How to read a line, a number, or all of standard input in Rust with read_line, trim, parse and lines(), and how to handle bad input.
- Functions in Rust: parameters, return values and expressions: How to write Rust functions with typed parameters and return values, why the last line has no semicolon, and expressions vs statements.
- Rust error E0308: mismatched types: What Rust's E0308 mismatched types error means, how to read expected vs found, and fixes for the most common causes.
- Threads in Rust: thread::spawn, join and move closures: How to run code in parallel with std::thread in Rust: spawn and join, returning values, move closures, scoped threads, and the E0373 error.
- Arc<Mutex<T>> in Rust: sharing mutable state between threads: How to share and change data across threads in Rust with Arc and Mutex, how lock guards work, poisoning, RwLock, atomics, and avoiding deadlocks.
- Channels in Rust: message passing with mpsc: How to send data between threads with std::sync::mpsc channels in Rust: send and recv, multiple producers, iterating the receiver, and bounded channels.
- Send and Sync in Rust explained: What the Send and Sync traits mean in Rust, which types are not Send or Sync (Rc, RefCell, Cell), and how to fix 'cannot be sent between threads safely'.
- Async/await in Rust with Tokio: the basics: Getting started with async Rust: futures, async fn and .await, #[tokio::main], tokio::spawn, join!, async sleep, and when to use async vs threads.
- Structs and impl blocks in Rust: methods and associated functions: How to define a struct in Rust, add methods with impl, choose between &self, &mut self and self, and write a new() constructor.
- Enums in Rust: variants that carry data: Rust enums explained: defining variants with and without data, matching on them, methods on enums, and modeling states that can't go wrong.
- Match in Rust: pattern matching explained: How Rust's match works: literals, ranges, | alternatives, guards, @ bindings, destructuring tuples, structs and enums, and exhaustiveness.
- Option in Rust: Some, None and handling missing values: How Rust's Option<T> replaces null: Some and None, match and if let, unwrap_or, map, and_then, the ? operator, and when unwrap is OK.
- Vec in Rust: creating, adding, removing and iterating: A practical guide to Rust's Vec<T>: vec!, push and pop, get vs indexing, insert and remove, sort, retain, dedup, and with_capacity.
- HashMap in Rust: insert, get and the entry API: How to use HashMap in Rust: insert, get, contains_key, remove, counting with entry().or_insert(), and printing keys in a stable order.
- Iterating over collections in Rust: iter, iter_mut and into_iter: The three ways to loop over a Vec, array or HashMap in Rust: &v (iter), &mut v (iter_mut) and v (into_iter), plus enumerate, zip and rev.
- Why you can't index a String in Rust (UTF-8, chars and bytes): Why s[0] doesn't compile for a Rust String, how UTF-8 works, and how to get characters with chars(), char_indices() and safe slicing.
- Closures in Rust and the Fn, FnMut and FnOnce traits: How Rust closures capture variables, the difference between Fn, FnMut and FnOnce, the move keyword, and passing or returning closures.
- Iterators in Rust: map, filter, collect and other adapters: How Rust iterators work: the Iterator trait, lazy adapters like map, filter and enumerate, consumers like collect, sum and fold, and writing your own.
- Modules and visibility in Rust: mod, pub and use: How Rust modules work: mod blocks and files, private by default, pub and pub(crate), paths with crate:: and super::, use, and re-exports.
- Box, Rc and RefCell in Rust: smart pointers explained: When to use Box<T>, Rc<T>, RefCell<T>, Rc<RefCell<T>> and Weak<T> in Rust, with the trade-offs and the runtime borrow panic to avoid.
- Unit testing in Rust: #[test], assert_eq! and cargo test: How to write tests in Rust: #[test] functions, assert!, assert_eq! with messages, should_panic, tests returning Result, and unit vs integration tests.
- Ownership and moves in Rust: Rust's ownership rules explained: one owner per value, moves on assignment and function calls, drop at end of scope, and how to fix use after move.
- Copy vs Clone in Rust: The difference between Copy and Clone in Rust: implicit bitwise copies vs explicit .clone(), which types are Copy, and when to derive each.
- Borrowing and references in Rust (&T and &mut T): How borrowing works in Rust: shared references &T, mutable references &mut T, the one writer or many readers rule, and dereferencing with *.
- Slices in Rust: &str, &[T] and ranges: What slices are in Rust, how to take &s[a..b] and &v[a..b], why &str and &[T] make better parameters, and the panics to avoid.
- Stack vs heap in Rust: Where Rust stores your data: the stack for fixed-size values, the heap for String, Vec and Box, how ownership frees heap memory, and the costs.
- Rust error E0382: borrow of moved value (use of moved value): Fix Rust's E0382 borrow of moved value and use of moved value errors: why values move, the common causes, and the right fix for each.
- Rust error E0502: cannot borrow as mutable because it is also borrowed as immutable: Why Rust reports E0502 when you modify a Vec or String while a reference to it is alive, and five ways to fix it.
- Rust error E0499: cannot borrow as mutable more than once at a time: What E0499 means in Rust, why two &mut references to the same value are forbidden, and fixes like split_at_mut, swap and field borrows.
- Rust error E0596: cannot borrow as mutable, as it is not declared as mutable: Fix Rust's E0596 error: add mut to the variable, take &mut in the function signature, or make a mutating closure mut.
- Rust error E0597: borrowed value does not live long enough: Why Rust says a borrowed value does not live long enough (E0597), with fixes for inner scopes, loops that store references, and returning references.
- Rust error E0106: missing lifetime specifier: How to fix Rust's E0106 missing lifetime specifier: adding <'a> to functions and structs, the elision rules, and when to return owned data.
- Rust error E0507: cannot move out of borrowed content (behind a reference): Fix Rust's E0507 cannot move out of index, behind a shared reference: borrow, clone, as_ref, take or mem::replace.
- Serde JSON in Rust: serialize and deserialize structs: How to convert Rust structs to and from JSON with serde and serde_json: derive, to_string, from_str, rename, Option fields, defaults and errors.
- anyhow vs thiserror in Rust: which should you use?: The difference between anyhow and thiserror for Rust error handling, when to use each, with context(), bail!, #[error] and #[from] examples.
- Cargo.toml explained: dependencies, versions and features: A practical guide to Cargo.toml: package metadata, dependency version requirements (semver), features, dev-dependencies, profiles and Cargo.lock.
- Clippy and rustfmt: linting and formatting Rust code: How to use cargo clippy and cargo fmt: the most common clippy suggestions with before and after code, lint levels, configuration, and running both in CI.
- macro_rules! in Rust: writing your own macros: How to write declarative macros in Rust with macro_rules!: matchers, fragment specifiers like expr and ident, repetition with $(...),*, and when to use them.
- Unsafe Rust: what it allows and when to use it: What the unsafe keyword actually permits in Rust, raw pointers, unsafe functions, FFI, writing safe abstractions with SAFETY comments, and when it's justified.
- Rust performance tips: release builds, allocations and iterators: Practical ways to make Rust code faster: build with --release, measure first, avoid needless clones and allocations, pre-size collections, buffer output.