Welcome to Rust
Rust is a modern systems programming language that focuses on performance, reliability, and productivity. Developed by Mozilla Research, Rust provides memory safety without garbage collection through its innovative ownership system.
Known for its "fearless concurrency" and zero-cost abstractions, Rust enables developers to write efficient, safe code while preventing common programming errors like null pointer dereferences, buffer overflows, and data races. This makes Rust ideal for systems programming, web assembly, embedded systems, and performance-critical applications.
Introduction to Rust
How to set up a Rust development environment and write your first "Hello, World!" program.
Rust is designed to be safe, concurrent, and practical. Setting up a Rust development environment is straightforward with the official Rust toolchain.
Step 1: Install Rust
-
All Platforms
Use rustup, the Rust toolchain installer. Open your terminal and run:shcurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shOr on Windows, download and run the rustup-init.exe from rustup.rs.
Step 2: Verify Installation
Open a terminal and type:
shrustc --version
This should display the installed Rust compiler version.
Step 3: Create and Run Your First Rust Program
-
Create a new Rust project using Cargo:
shcargo new hello_world cd hello_world -
Examine the generated
src/main.rsfile:rustfn main() { println!("Hello, world!"); } -
Run the program:
shcargo runYou should see the output:
Hello, world!
Congratulations! You have successfully set up a Rust environment and run your first program. 🎉
Rust Syntax Basics
Rust syntax is designed to be expressive and safe. Understanding the basic syntax is crucial for writing correct Rust programs.
1. Basic Structure of a Rust Program
Every Rust program has a specific structure:
rustfn main() { // Main function - program entry point
// Program statements go here
println!("Hello, Rust!");
}
2. Semicolons and Blocks
Rust uses semicolons to terminate statements and braces {} to define code blocks:
rustlet x = 5; // Statement ends with semicolon
if x > 3 { // Braces define the if block
println!("x is greater than 3");
} // Closing brace
3. Comments
Rust supports single-line and documentation comments:
rust// This is a single-line comment
/// This is a documentation comment
/// It supports Markdown and is used by rustdoc
fn my_function() {
/*
This is a multi-line comment
It can span multiple lines
*/
}
4. Case Sensitivity
Rust is case-sensitive, meaning it distinguishes between uppercase and lowercase letters:
rustlet my_var = 5; // Different from myvar
let MyVar = 10; // Different from myVar
println!("{}", my_var); // Outputs: 5
println!("{}", MyVar); // Outputs: 10
5. Variables and Type Inference
Rust has strong, static typing with excellent type inference:
rustlet x = 10; // Compiler infers i32
let y = 3.14; // Compiler infers f64
let z = 'A'; // Character
let name = "Rust"; // String slice &str
// Explicit type annotation
let a: i32 = 10;
let b: f64 = 3.14;
let c: char = 'A';
let d: &str = "Rust";
Conclusion
Understanding Rust syntax is essential for writing correct and efficient programs. Key takeaways include:
- Rust programs start execution from the
main()function - Statements end with semicolons
- Code blocks are defined with braces
{} - Rust is case-sensitive
- Rust has strong static typing with excellent type inference
Output with println!
The println! macro in Rust is used to display output on the screen. It's one of the most commonly used features for basic output and debugging.
1. Basic println! Usage
The simplest way to use println! is with string literals:
rustfn main() {
println!("Hello, World!"); // Outputs: Hello, World!
println!("{}", 42); // Outputs: 42
}
2. Formatting with Placeholders
You can use placeholders to format output:
rustprintln!("Hello {}!", "Rust"); // Outputs: Hello Rust!
println!("{} + {} = {}", 5, 3, 8); // Outputs: 5 + 3 = 8
3. Positional and Named Arguments
Rust supports positional and named arguments in formatting:
rust// Positional arguments
println!("{0} {1} {0}", "foo", "bar"); // Outputs: foo bar foo
// Named arguments
println!("{name} is {age} years old", name = "Alice", age = 25);
4. Formatting Specifiers
Rust provides various formatting specifiers for different data types:
rustlet number = 42;
let float = 3.14159;
println!("Decimal: {}", number); // 42
println!("Binary: {:b}", number); // 101010
println!("Hex: {:x}", number); // 2a
println!("Octal: {:o}", number); // 52
println!("Float: {:.2}", float); // 3.14
println!("Scientific: {:e}", float); // 3.14159e0
5. Printing Variables and Expressions
You can print variables and expressions:
rustlet name = "Alice";
let age = 25;
println!("Name: {}, Age: {}", name, age);
// Expressions work too
println!("5 + 3 = {}", 5 + 3);
6. Debug and Display Traits
rust#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
let point = Point { x: 10, y: 20 };
// Debug formatting
println!("{:?}", point); // Outputs: Point { x: 10, y: 20 }
println!("{:#?}", point); // Pretty-print:
// Point {
// x: 10,
// y: 20,
// }
Conclusion
The println! macro is a fundamental tool for output in Rust. Key points:
- Use
{}as placeholders for values - Supports positional and named arguments
- Rich formatting options for different data types
- Can print debug information with
{:?}
Arithmetic Operators in Rust
Rust provides standard arithmetic operators for mathematical calculations. These operators work with numeric data types like integers and floating-point numbers.
Basic Arithmetic Operators
rustfn main() {
let a = 15;
let b = 4;
println!("a + b = {}", a + b); // Addition: 19
println!("a - b = {}", a - b); // Subtraction: 11
println!("a * b = {}", a * b); // Multiplication: 60
println!("a / b = {}", a / b); // Division: 3 (integer division)
println!("a % b = {}", a % b); // Modulus: 3
let x = 15.0;
let y = 4.0;
println!("x / y = {}", x / y); // Division: 3.75 (float division)
}
Type Considerations
rust// Rust requires explicit type conversion
let a: i32 = 10;
let b: f64 = 3.14;
// This would cause a compile error:
// let result = a + b;
// Correct approach with explicit conversion
let result = a as f64 + b;
println!("Result: {}", result); // 13.14
Overflow Handling
rustlet max_u8 = 255u8;
// This would panic in debug mode or wrap in release mode
// let overflow = max_u8 + 1;
// Safe arithmetic operations
let checked = max_u8.checked_add(1); // Returns None
let wrapping = max_u8.wrapping_add(1); // Returns 0
let saturating = max_u8.saturating_add(1); // Returns 255
println!("Checked: {:?}", checked); // None
println!("Wrapping: {}", wrapping); // 0
println!("Saturating: {}", saturating); // 255
Common Pitfalls
- Integer division truncates the fractional part:
5 / 2equals2, not2.5 - Mixing different numeric types requires explicit conversion
- Division by zero causes a panic at runtime
- Integer overflow behavior depends on compilation mode
Comparison Operators in Rust
Comparison operators compare two values and return a boolean result (true or false). These are essential for conditional statements and loops.
Comparison Operators
rustfn main() {
let x = 7;
let y = 10;
println!("x == y: {}", x == y); // Equal to: false
println!("x != y: {}", x != y); // Not equal to: true
println!("x > y: {}", x > y); // Greater than: false
println!("x < y: {}", x < y); // Less than: true
println!("x >= 7: {}", x >= 7); // Greater than or equal: true
println!("y <= 7: {}", y <= 7); // Less than or equal: false
// Comparing different types requires conversion
let int_val: i32 = 5;
let float_val: f64 = 5.0;
// This works because we convert to the same type
println!("Equal: {}", int_val as f64 == float_val); // true
}
Using Comparisons in Conditions
rustlet age = 18;
if age >= 18 {
println!("You are an adult");
} else {
println!("You are a minor");
}
// Pattern matching with comparisons
match age {
0..=17 => println!("Minor"),
18..=64 => println!("Adult"),
_ => println!("Senior"),
}
Comparing Custom Types
rust#[derive(PartialEq, PartialOrd)]
struct Point {
x: i32,
y: i32,
}
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
// Now we can compare Point instances
println!("p1 == p2: {}", p1 == p2); // false
// println!("p1 < p2: {}", p1 < p2); // This would need FullOrd derivation
Common Pitfalls
- Comparing different numeric types requires explicit conversion
- Custom types need to derive comparison traits to use operators
- Floating-point comparisons for exact equality can be problematic due to precision issues
- NaN values always compare as not equal, even to themselves
Logical Operators in Rust
Logical operators combine boolean expressions and return true or false. Rust provides three logical operators: && (AND), || (OR), and ! (NOT).
Logical Operators
rustfn main() {
let is_sunny = true;
let is_warm = false;
println!("is_sunny && is_warm: {}", is_sunny && is_warm); // AND: false
println!("is_sunny || is_warm: {}", is_sunny || is_warm); // OR: true
println!("!is_warm: {}", !is_warm); // NOT: true
// Complex conditions
let age = 25;
let has_license = true;
if age >= 18 && has_license {
println!("You can drive");
}
}
Short-Circuit Evaluation
rust// In AND (&&), if first condition is false, second isn't evaluated
// In OR (||), if first condition is true, second isn't evaluated
fn expensive_check() -> bool {
println!("Expensive check performed!");
true
}
let x = false;
if x && expensive_check() { // expensive_check() not called
println!("This won't execute");
}
let y = true;
if y || expensive_check() { // expensive_check() not called
println!("This will execute without calling expensive_check");
}
Boolean Operations on Other Types
rust// Option and Result types have boolean-like operations
let some_value: Option<i32> = Some(5);
let none_value: Option<i32> = None;
// Using and_then, or_else for chaining operations
let result = some_value.and_then(|x| Some(x * 2)); // Some(10)
let result2 = none_value.and_then(|x| Some(x * 2)); // None
println!("Result: {:?}", result);
println!("Result2: {:?}", result2);
Common Pitfalls
- Using bitwise operators (
&,|) instead of logical operators (&&,||) - Forgetting that logical operators only work with boolean types
- Not leveraging short-circuit evaluation for performance
Bitwise Operators in Rust
Bitwise operators perform operations on individual bits of integer types. They are used in low-level programming, embedded systems, and performance optimization.
Bitwise Operators
rustfn main() {
let a: u8 = 0b0110; // binary: 0110 (6)
let b: u8 = 0b0011; // binary: 0011 (3)
println!("a = {:08b} ({})", a, a);
println!("b = {:08b} ({})", b, b);
println!("a & b = {:08b} ({})", a & b, a & b); // AND: 0010 (2)
println!("a | b = {:08b} ({})", a | b, a | b); // OR: 0111 (7)
println!("a ^ b = {:08b} ({})", a ^ b, a ^ b); // XOR: 0101 (5)
println!("!a = {:08b} ({})", !a, !a); // NOT: 11111001 (249)
println!("a << 1 = {:08b} ({})", a << 1, a << 1); // Left shift: 1100 (12)
println!("b >> 1 = {:08b} ({})", b >> 1, b >> 1); // Right shift: 0001 (1)
}
Practical Applications
rust// Setting and checking flags
const FLAG_A: u8 = 1 << 0; // 0001
const FLAG_B: u8 = 1 << 1; // 0010
const FLAG_C: u8 = 1 << 2; // 0100
let mut settings = 0;
settings |= FLAG_A; // Set flag A
settings |= FLAG_C; // Set flag C
// Check if flag B is set
if settings & FLAG_B != 0 {
println!("Flag B is set");
} else {
println!("Flag B is not set");
}
// Count set bits (population count)
let value: u32 = 0b10101100;
let count = value.count_ones();
println!("Number of set bits in {}: {}", value, count);
Bit Manipulation Methods
rustlet num: u8 = 0b10101010;
// Various bit manipulation methods
println!("Leading zeros: {}", num.leading_zeros());
println!("Trailing zeros: {}", num.trailing_zeros());
println!("Count ones: {}", num.count_ones());
println!("Rotate left: {:08b}", num.rotate_left(2));
println!("Swap bytes: {:08b}", num.swap_bytes());
// Check power of two
let power_of_two = 16u32;
println!("{} is power of two: {}", power_of_two, power_of_two.is_power_of_two());
Common Pitfalls
- Confusing bitwise AND
&with logical AND&& - Shift operations on signed integers maintain sign (arithmetic shift)
- Shifting beyond the bit width causes panic in debug mode
- Forgetting that bitwise NOT on signed integers also flips the sign bit
Assignment Operators in Rust
Assignment operators assign values to variables. Rust provides compound assignment operators that combine assignment with arithmetic or bitwise operations.
Assignment Operators
rustfn main() {
let mut x = 10; // Simple assignment
println!("x = {}", x);
x += 5; // Equivalent to x = x + 5
println!("x += 5: {}", x); // 15
x -= 3; // Equivalent to x = x - 3
println!("x -= 3: {}", x); // 12
x *= 2; // Equivalent to x = x * 2
println!("x *= 2: {}", x); // 24
x /= 4; // Equivalent to x = x / 4
println!("x /= 4: {}", x); // 6
x %= 4; // Equivalent to x = x % 4
println!("x %= 4: {}", x); // 2
// Bitwise assignment operators
let mut y: u8 = 5;
y &= 3; // AND assignment: y = y & 3
y |= 8; // OR assignment: y = y | 8
y ^= 4; // XOR assignment: y = y ^ 4
println!("Final y: {}", y);
}
Multiple Assignment and Destructuring
rust// Multiple assignment (destructuring)
let (a, b, c) = (10, 20, 30);
println!("a={}, b={}, c={}", a, b, c);
// Swap values
let mut x = 5;
let mut y = 10;
println!("Before: x={}, y={}", x, y);
std::mem::swap(&mut x, &mut y);
println!("After: x={}, y={}", x, y);
// Compound assignment in loops
let mut sum = 0;
for i in 1..=5 {
sum += i; // Add i to sum
}
println!("Sum: {}", sum); // 15
Assignment with Different Types
rust// Type conversion during assignment
let int_val: i32 = 42;
let float_val: f64 = int_val as f64; // Explicit conversion
// Assignment from function returns
let result = {
let x = 5;
let y = 10;
x + y // No semicolon - this expression is returned
};
println!("Result: {}", result); // 15
// Assignment with pattern matching
let (success, value) = if true {
(true, 42)
} else {
(false, 0)
};
println!("Success: {}, Value: {}", success, value);
Common Pitfalls
- Forgetting
mutkeyword when variable needs to be mutable - Trying to assign to immutable variables
- Mixing types in compound assignments without explicit conversion
- Shadowing variables instead of mutating them
Integer Data Types in Rust
Rust provides several integer types with explicit sizes and signed/unsigned variants. Choosing the right integer type depends on the required range and memory constraints.
Basic Integer Types
rustfn main() {
// Signed integers (can represent negative numbers)
let i8_val: i8 = 100; // 8-bit signed (-128 to 127)
let i16_val: i16 = 1000; // 16-bit signed
let i32_val: i32 = 100000; // 32-bit signed (default)
let i64_val: i64 = 100000; // 64-bit signed
let i128_val: i128 = 100000; // 128-bit signed
let isize_val: isize = 100000; // Architecture-dependent signed
// Unsigned integers (only non-negative numbers)
let u8_val: u8 = 100; // 8-bit unsigned (0 to 255)
let u16_val: u16 = 1000; // 16-bit unsigned
let u32_val: u32 = 100000; // 32-bit unsigned
let u64_val: u64 = 100000; // 64-bit unsigned
let u128_val: u128 = 100000; // 128-bit unsigned
let usize_val: usize = 100000; // Architecture-dependent unsigned
// Type inference
let inferred = 42; // Compiler infers i32
let explicit: u64 = 42; // Explicit type
println!("i8 range: {} to {}", i8::MIN, i8::MAX);
println!("u8 range: {} to {}", u8::MIN, u8::MAX);
println!("usize size: {} bytes", std::mem::size_of::<usize>());
}
Integer Operations
rustlet a = 10;
let b = 3;
println!("a + b = {}", a + b); // 13
println!("a - b = {}", a - b); // 7
println!("a * b = {}", a * b); // 30
println!("a / b = {}", a / b); // 3 (integer division)
println!("a % b = {}", a % b); // 1 (modulus)
// Checked operations (avoid panics)
match a.checked_add(b) {
Some(result) => println!("Safe addition: {}", result),
None => println!("Addition would overflow"),
}
// Wrapping operations
let wrapped = a.wrapping_add(b);
println!("Wrapped addition: {}", wrapped);
Type Conversion and Casting
rust// Safe casting between integer types
let small: u8 = 255;
let large: u16 = small as u16; // 255
// This would lose data but is allowed
let large_num: i32 = 300;
let small_num: u8 = large_num as u8; // 44 (300 - 256)
// String to integer
let str_val = "123";
let int_val: i32 = str_val.parse().unwrap(); // 123
let int_val2: i32 = "123".parse().expect("Not a number!");
// Different parsing approaches
let num1 = "42".parse::<i32>(); // Ok(42)
let num2 = "42abc".parse::<i32>(); // Err
Common Pitfalls
- Integer overflow panics in debug mode, wraps in release mode
- Integer division truncates fractional parts
- Casting between types can silently lose data
- Parsing strings can fail - always handle Result types
Floating-Point Data Types in Rust
Floating-point types represent real numbers with fractional parts. Rust provides two floating-point types with different precision levels.
Floating-Point Types
rustfn main() {
let f32_val: f32 = 3.14159; // Single precision (32 bits)
let f64_val: f64 = 3.14159265358979; // Double precision (64 bits, default)
// Type inference
let inferred_float = 3.14; // Compiler infers f64
println!("f32: {:.10}", f32_val);
println!("f64: {:.10}", f64_val);
// Special values
println!("sqrt(-1): {:?}", (-1.0f64).sqrt()); // NaN (Not a Number)
println!("1.0/0.0: {:?}", 1.0 / 0.0); // inf (Infinity)
println!("-1.0/0.0: {:?}", -1.0 / 0.0); // -inf
// Checking special values
let nan = f64::NAN;
println!("Is NaN: {}", nan.is_nan());
println!("Is finite: {}", f64_val.is_finite());
println!("Is infinite: {}", f64::INFINITY.is_infinite());
}
Floating-Point Operations
rustlet a = 2.5;
let b = 1.5;
println!("a + b = {}", a + b); // 4.0
println!("a - b = {}", a - b); // 1.0
println!("a * b = {}", a * b); // 3.75
println!("a / b = {}", a / b); // 1.6666666666666667
// Mathematical functions
println!("sqrt(a) = {}", a.sqrt());
println!("powf(a, b) = {}", a.powf(b));
println!("sin(pi/2) = {}", (std::f64::consts::PI / 2.0).sin());
// Rounding operations
let num = 3.75;
println!("floor: {}", num.floor()); // 3.0
println!("ceil: {}", num.ceil()); // 4.0
println!("round: {}", num.round()); // 4.0
println!("trunc: {}", num.trunc()); // 3.0
println!("fract: {}", num.fract()); // 0.75
Type Conversion and Precision
rust// String to floating-point
let str_val = "3.14159";
let float_val: f64 = str_val.parse().unwrap();
// Floating-point to integer (truncation)
let f = 3.99;
let i = f as i32; // i becomes 3
// Integer to floating-point
let x = 5;
let y = x as f64; // y becomes 5.0
// Be careful with precision
let precise: f64 = 0.1 + 0.2;
println!("0.1 + 0.2 = {}", precise); // 0.30000000000000004
println!("Equal to 0.3: {}", precise == 0.3); // false
// Better approach for comparisons
let tolerance = 1e-10;
println!("Close to 0.3: {}", (precise - 0.3).abs() < tolerance); // true
Common Pitfalls
- Floating-point numbers have limited precision and rounding errors
- Comparing floating-point numbers for exact equality is often problematic
- Operations with very large or very small numbers can cause overflow/underflow
- NaN values propagate through calculations and break comparisons
Rust’s standard library collections (Vec, HashMap) combined with lazy iterator adaptors provide a zero-cost abstraction pipeline for high-performance data transformation. Mastering these primitives allows you to write declarative code that compiles down to tight, vectorized loops comparable to hand-written C.
Anatomy of an Iterator Pipeline
Iterators in Rust are lazy; they do nothing until a consuming adaptor (like .collect(), .fold(), or .for_each()) is called. Intermediate adapters like .map(), .filter(), and .take() return lazy wrapper types that modify the iteration protocol without allocating new memory.
rustfn process_scores(scores: &[u32]) -> Vec<u32> {
scores.iter()
.filter(|&&score| score >= 50) // Lazy filter
.map(|&score| score * 2) // Lazy transformation
.rev() // Lazy reversal
.collect() // Consuming adaptor (triggers allocation)
}
fn main() {
let raw_scores = vec![30, 85, 45, 90, 60];
let processed = process_scores(&raw_scores);
println!("{:?}", processed);
}
Expected Output
```text [120, 180, 170] ```Hash Maps and Entry API Mutations
The HashMap collection provides $O(1)$ average time complexity for lookups and insertions. Idiomatic Rust avoids checking existence before insertion (if !map.contains_key()) by using the powerful Entry API, which performs lookups and mutations in a single pass.
rustuse std::collections::HashMap;
fn count_words(text: &str) -> HashMap<&str, usize> {
let mut word_counts = HashMap::new();
for word in text.split_whitespace() {
// Entry API handles checking and default allocation cleanly
*word_counts.entry(word).or_insert(0) += 1;
}
word_counts
}
fn main() {
let passage = "rust is fast and rust is safe";
let counts = count_words(passage);
println!("'rust' appears {} times.", counts.get("rust").unwrap_or(&0));
}
Expected Output
```text 'rust' appears 2 times. ```Performance Considerations and Gotchas
- Pre-allocation: When collecting into a
Vecor populating aHashMapwhere the final size is known or can be estimated, useVec::with_capacity(n)orHashMap::with_capacity(n)to eliminate costly reallocations and memory growth penalties. - Ownership vs Borrowing: Prefer
.iter()(borrows references) over.into_consumer()or iterating directly on collections when you only need to read data, unless you explicitly intend to consume and transfer ownership of the elements. - DoS Vulnerability in HashMaps: Rust’s standard
HashMapuses SipHash 1-3 by default, which defends against Hash-DoS attacks. If you are operating on massive keys in a performance-critical inner loop where cryptographic security is irrelevant, consider using an alternative hasher from crates likefxhashorahash.
Key Takeaways
- Iterator chains are lazy; execution is deferred until a consuming adapter like
.collect()is invoked. - Intermediate iterator adapters introduce zero runtime overhead compared to manual loops due to aggressive compiler inlining and dead code elimination.
- The
HashMap::entryAPI prevents redundant lookups, making updates cleaner and more performant. - Always pre-allocate collection capacities if the target size is known to prevent runtime reallocations.
Strings in Rust
Rust has two main string types: String (owned, growable) and &str (string slice, borrowed). Understanding both is crucial for effective Rust programming.
Creating and Using Strings
rustfn main() {
// Different ways to create strings
let s1 = String::from("Hello");
let s2 = "World".to_string();
let s3 = String::new();
let s4 = "String slice"; // This is &str, not String
// Concatenation
let s5 = s1 + " " + &s2; // Note: s1 is moved here
println!("s5: {}", s5);
// Format macro for complex concatenation
let s6 = format!("{} {}!", "Hello", "Rust");
println!("s6: {}", s6);
// String slices (&str)
let slice = "Hello World";
let hello = &slice[0..5]; // "Hello"
let world = &slice[6..11]; // "World"
println!("hello: {}, world: {}", hello, world);
// String length and capacity
let mut text = String::from("Hello");
println!("Length: {}", text.len()); // 5
println!("Capacity: {}", text.capacity()); // 5
println!("Is empty: {}", text.is_empty()); // false
text.push_str(" Rust!");
println!("After push_str: {}", text); // Hello Rust!
}
String Comparison and Searching
rustlet str1 = "apple";
let str2 = "banana";
// Comparison
if str1 == str2 {
println!("Strings are equal");
} else if str1 < str2 {
println!("{} comes before {}", str1, str2);
} else {
println!("{} comes after {}", str1, str2);
}
// Searching
let text = "Hello World";
if let Some(pos) = text.find("World") {
println!("Found 'World' at position {}", pos);
}
// Pattern matching with contains
if text.contains("Hello") {
println!("Text contains 'Hello'");
}
// Starts with / ends with
println!("Starts with 'Hello': {}", text.starts_with("Hello"));
println!("Ends with 'World': {}", text.ends_with("World"));
String Modification
rustlet mut text = String::from("Hello");
// Append characters and strings
text.push('!'); // Add single character
text.push_str(" Rust"); // Add string slice
// Insert at position
text.insert(5, ','); // Insert character at index 5
text.insert_str(6, " dear"); // Insert string at index 6
// Replace
let replaced = text.replace("dear", "wonderful");
// Remove characters
let mut remove_example = String::from("Hello");
let removed_char = remove_example.remove(4); // Removes 'o' at index 4
remove_example.pop(); // Remove last character
println!("Modified: {}", text);
println!("Replaced: {}", replaced);
println!("After removal: {}", remove_example);
Iterating Over Strings
rustlet text = "Hello 世界"; // Mix of ASCII and non-ASCII
// Iterate by characters (Unicode scalar values)
println!("Characters:");
for c in text.chars() {
print!("{} ", c);
}
println!();
// Iterate by bytes
println!("Bytes:");
for b in text.bytes() {
print!("{} ", b);
}
println!();
// Iterate with indices
for (i, c) in text.char_indices() {
println!("Character at {}: {}", i, c);
}
Common Pitfalls
- Indexing strings with
[]is not allowed - use slicing with caution - String slices must occur on valid UTF-8 boundaries
- Confusing
String(owned) with&str(borrowed) - Forgetting that some string operations move ownership
Rust closures are anonymous functions that capture their environment, backed by three fundamental traits (Fn, FnMut, FnOnce) and governed by precise lifetime elision rules when capturing references.
Closure Traits: Fn, FnMut, and FnOnce
Rust automatically implements closure traits based on how a closure captures and uses its environment.
FnOnce: Consumes captured variables by value. It can be called at least once. All closures implement this trait.FnMut: Mutably borrows captured variables. It can be called multiple times without consuming them.FnFn: (Written simply asFn) Immortally or immutably borrows captured variables. It can be called concurrently or repeatedly without mutating state.
rustfn execute_once<F: FnOnce()>(f: F) {
f();
}
fn execute_mutable<F: FnMut()>(mut f: F) {
f();
f();
}
fn main() {
let text = String::from("Old Lane 17");
// FnOnce: consumes 'text' by moving it
let consume_text = || {
let _t = text;
println!("Consumed!");
};
execute_once(consume_text);
// println!("{}", text); // Error: 'text' was moved!
let mut counter = 0;
// FnMut: mutably borrows 'counter'
let mut increment = || {
counter += 1;
println!("Counter: {}", counter);
};
execute_mutable(&mut increment);
}
Advanced Lifetime Elision and Higher-Ranked Trait Bounds (HRTB)
When closures accept references as arguments, the compiler applies lifetime elision. However, when passing closures to higher-order functions, you often need to express that a closure must handle any lifetime, utilizing Higher-Ranked Trait Bounds with the for<'_> syntax.
rust// A function that accepts any closure taking a reference with *any* lifetime
fn process_with_ref<F>(f: F)
where
F: for<'a> Fn(&'a str) -> usize,
{
println!("Length: {}", f("Old Lane 17"));
}
fn main() {
// The closure parameter s can take a reference of any lifetime
process_with_ref(|s| s.len());
}
Common Gotchas & Performance Tips
- Trait Selection: Always bound your generic parameters with the most restrictive trait possible (
FnoverFnMut, andFnMutoverFnOnce) to maximize caller flexibility. - Performance: Closures compile down to unique, anonymous structs. They are zero-cost abstractions: Rust monomorphizes closure calls, enabling aggressive inlining by the LLVM backend.
- Explicit Move Keywords: Use
moveclosures when sending data across thread boundaries (e.g.,std::thread::spawn) to force the closure to take ownership of its captured variables rather than borrowing them.
Expected Output
textConsumed!
Counter: 1
Counter: 2
Length: 11
Key Takeaways
Fn,FnMut, andFnOnceform a inheritance hierarchy:FnrequiresFnMut, which requiresFnOnce.- Compiler trait selection for closures is determined strictly by analysis of variable usage inside the closure body.
- Use
for<'a>(HRTBs) when writing higher-order functions that accept closures handling references of arbitrary lifetimes. - Closures have zero runtime overhead compared to manual struct definitions and function pointers.
String Functions in Rust
Rust's String type provides many useful methods for string manipulation, including trimming, case conversion, splitting, and pattern matching.
String Manipulation Methods
rustfn main() {
let text = " Hello World ";
// Trimming
let trimmed = text.trim();
println!("Trimmed: '{}'", trimmed); // 'Hello World'
let left_trimmed = text.trim_start();
let right_trimmed = text.trim_end();
println!("Left trimmed: '{}'", left_trimmed);
println!("Right trimmed: '{}'", right_trimmed);
// Case conversion
let mixed = "Hello World";
let uppercase = mixed.to_uppercase();
let lowercase = mixed.to_lowercase();
println!("Uppercase: {}", uppercase); // HELLO WORLD
println!("Lowercase: {}", lowercase); // hello world
// Repeat strings
let repeated = "abc".repeat(3);
println!("Repeated: {}", repeated); // abcabcabc
}
String Splitting and Joining
rust// Splitting a string
let data = "apple,banana,cherry";
let fruits: Vec<&str> = data.split(',').collect();
println!("Fruits: {:?}", fruits); // ["apple", "banana", "cherry"]
// Splitting with multiple delimiters
let text = "apple, banana; cherry";
let items: Vec<&str> = text.split([',', ';']).map(|s| s.trim()).collect();
println!("Items: {:?}", items); // ["apple", "banana", "cherry"]
// Splitting into lines
let multiline = "Line 1\nLine 2\nLine 3";
for line in multiline.lines() {
println!("Line: {}", line);
}
// Joining strings
let joined = fruits.join("-");
println!("Joined: {}", joined); // apple-banana-cherry
// Using collect to join
let collected: String = fruits.into_iter().collect();
println!("Collected: {}", collected); // applebananacherry
Pattern Matching with Strings
rustlet text = "The quick brown fox";
// Using patterns with string methods
let words: Vec<&str> = text.split_whitespace().collect();
println!("Words: {:?}", words);
// Matching with patterns
match text {
"hello" => println!("It's hello!"),
s if s.starts_with("The") => println!("Starts with 'The'"),
s if s.contains("fox") => println!("Contains 'fox'"),
_ => println!("Something else"),
}
// Using matches! macro
if text.matches("o").count() == 3 {
println!("Text contains exactly three 'o' characters");
}
String Validation and Inspection
rustlet text = "Hello123";
// Checking string properties
println!("Is ASCII: {}", text.is_ascii());
println!("Is empty: {}", text.is_empty());
println!("Length: {}", text.len());
println!("Number of chars: {}", text.chars().count());
// Checking character categories
println!("All alphabetic: {}", text.chars().all(|c| c.is_alphabetic()));
println!("Any digit: {}", text.chars().any(|c| c.is_numeric()));
// Finding positions
if let Some(pos) = text.find('1') {
println!("First digit at position: {}", pos);
}
// RFind (reverse find)
if let Some(pos) = text.rfind('l') {
println!("Last 'l' at position: {}", pos);
}
Common Pitfalls
- String indexing is not allowed - use
chars()or pattern matching - Slicing can panic if not on character boundaries
split()returns an iterator, need tocollect()to get Vec- Some operations consume the string, others work on references
Rust macros are syntactic meta-programming tools that generate and expand code at compile-time, eliminating repetitive boilerplate without runtime overhead. Declarative macros, built using macro_rules!, use pattern matching over token trees to write safe, hygienic code generators.
The Anatomy of macro_rules!
A declarative macro matches incoming token streams against a set of patterns and expands them into target Rust code. Hygiene ensures that variables defined inside a macro cannot accidentally capture or conflict with variables in the calling scope.
rustmacro_rules! vec_strs {
// Match zero or more expressions separated by commas
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push(String::from($x));
)*
temp_vec
}
};
}
fn main() {
let names = vec_strs!["Alice", "Bob", "Charlie"];
println!("{:?}", names);
}
Expected Output
text["Alice", "Bob", "Charlie"]
Macro Metavariables and Repetition Specifiers
Rust macros use specifiers to dictate what kind of syntax a fragment matches. Common specifiers include:
expr: An expression (e.g.,2 + 2,"hello",x)ident: An identifier (e.g., variable name, function name)ty: A type (e.g.,i32,String,Vec<T>)path: A path (e.g.,std::cmp::Ordering)
Repetition operators handle lists and variadic inputs:
*: Zero or more times+: One or more times- A trailing separator (like
,) can be specified between repetitions (e.g.,$( $x:expr ),*).
Practical Example: Generating Boilerplate Getters
Here is a practical macro to automate generating simple getter methods for struct fields, preventing repetitive method-writing.
rustmacro_rules! make_getters {
($struct_name:ident { $( $field:ident : $ftype:ty ),* $(,)? }) => {
impl $struct_name {
$(
pub fn $field(&self) -> &$ftype {
&self.$field
}
)*
}
};
}
struct User {
id: u64,
username: String,
}
make_getters! {
User {
id: u64,
username: String,
}
}
fn main() {
let user = User { id: 42, username: String::from("ferris") };
println!("ID: {}, Username: {}", user.id(), user.username());
}
Common Gotchas and Performance Considerations
- Compile Times: Heavy macro usage increases compilation times because the compiler must expand and type-check macro code across multiple expansion passes.
- Debugging Complexity: Macro expansions are hard to debug when syntax errors occur. Use
cargo rustc -- -Z unstable-options --pretty=expandedto inspect how macros expand into raw code. - Overuse: If a problem can be solved with standard generics, traits, or functions, prefer them over macros for better IDE support and clearer error messages.
Key Takeaways
- Declarative macros (
macro_rules!) match token patterns and expand into native Rust code at compile time. - Hygiene prevents variable capture collisions between the macro body and the caller’s scope.
- Use metavariables like
$x:exprand$t:tycombined with repetition operators (*,+) to handle variadic code generation safely. - Prefer standard language constructs (traits, generics) when possible to maintain simpler compiler diagnostics and faster build times.
String Formatting in Rust
Rust provides powerful string formatting through the format! macro and related formatting traits. This allows for flexible and type-safe string creation.
Basic Formatting with format!
rustfn main() {
let name = "Alice";
let age = 25;
let score = 95.5;
// Basic formatting
let message = format!("Name: {}, Age: {}, Score: {}", name, age, score);
println!("{}", message);
// Positional arguments
let pos_message = format!("{0} {1} {0}", "foo", "bar");
println!("{}", pos_message); // foo bar foo
// Named arguments
let named_message = format!("{name} is {age} years old", name = "Bob", age = 30);
println!("{}", named_message);
}
Formatting Specifiers
rustlet number = 42;
let float = 3.14159;
// Number formatting
println!("Decimal: {}", number); // 42
println!("Binary: {:b}", number); // 101010
println!("Hex: {:x}", number); // 2a
println!("Hex uppercase: {:X}", number); // 2A
println!("Octal: {:o}", number); // 52
println!("Pointer: {:p}", &number); // memory address
// Float formatting
println!("Float: {}", float); // 3.14159
println!("Float 2 decimal: {:.2}", float); // 3.14
println!("Scientific: {:e}", float); // 3.14159e0
println!("Scientific upper: {:E}", float); // 3.14159E0
// Padding and alignment
println!("Right aligned: {:>10}", number); // " 42"
println!("Left aligned: {:<10}", number); // "42 "
println!("Center aligned: {:^10}", number); // " 42 "
println!("Zero padded: {:010}", number); // "0000000042"
Custom Formatting with Traits
rustuse std::fmt;
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
// Implement Display trait for custom formatting
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
let point = Point { x: 10, y: 20 };
// Using Display trait (user-facing)
println!("Point: {}", point); // Point: (10, 20)
// Using Debug trait (developer-facing)
println!("Point: {:?}", point); // Point: Point { x: 10, y: 20 }
println!("Point: {:#?}", point); // Pretty-printed:
// Point {
// x: 10,
// y: 20,
// }
}
Advanced Formatting Options
rustlet value = 255;
// Formatting with different bases
println!("Decimal: {}", value); // 255
println!("Binary: {:b}", value); // 11111111
println!("Hex: {:x}", value); // ff
println!("Hex with prefix: {:#x}", value); // 0xff
println!("Octal: {:o}", value); // 377
println!("Octal with prefix: {:#o}", value); // 0o377
// Formatting with sign
let positive = 42;
let negative = -42;
println!("Positive: {:+}", positive); // +42
println!("Negative: {:+}", negative); // -42
// Formatting with thousands separator (using crate)
// Typically you'd use a formatting crate for this
// Conditional formatting
let maybe_value = Some(42);
println!("Option: {:?}", maybe_value); // Some(42)
println!("Option: {}", maybe_value.unwrap_or(0)); // 42
Formatting Collections
rustlet numbers = vec![1, 2, 3, 4, 5];
let words = vec!["apple", "banana", "cherry"];
// Formatting vectors
println!("Numbers: {:?}", numbers); // [1, 2, 3, 4, 5]
println!("Numbers: {:#?}", numbers); // Pretty-printed
println!("Words: {}", words.join(", ")); // apple, banana, cherry
// Custom collection formatting
let formatted = format!("First: {}, Last: {}", numbers[0], numbers[numbers.len() - 1]);
println!("{}", formatted); // First: 1, Last: 5
// Using iterators with format
let squares: Vec<String> = numbers.iter()
.map(|&x| format!("{}²={}", x, x*x))
.collect();
println!("Squares: {}", squares.join(", "));
Common Pitfalls
- Forgetting that format! returns a String, doesn't print
- Mixing up Display (
{}) and Debug ({:?}) formatting - Format strings are checked at compile time - invalid formats cause errors
- Custom types need to implement Display or Debug for formatting
Arrays in Rust
Arrays are fixed-size collections of elements of the same type stored in contiguous memory. Rust arrays have a compile-time fixed size and are stack-allocated.
Fixed-Size Arrays
rustfn main() {
// Declaration and initialization
let numbers: [i32; 5] = [1, 2, 3, 4, 5]; // Type annotation
let inferred = [1, 2, 3, 4, 5]; // Type inferred as [i32; 5]
let same_value = [0; 5]; // [0, 0, 0, 0, 0]
// Accessing elements
println!("First element: {}", numbers[0]); // 1
println!("Last element: {}", numbers[4]); // 5
// Modifying elements (array must be mutable)
let mut mutable_array = [1, 2, 3, 4, 5];
mutable_array[2] = 100;
println!("Modified: {:?}", mutable_array);
// Array size
println!("Array length: {}", numbers.len());
// Iterating through array
println!("Array elements:");
for i in 0..numbers.len() {
println!("numbers[{}] = {}", i, numbers[i]);
}
// Better: using iterators
for element in &numbers {
println!("Element: {}", element);
}
// With enumerate for index
for (i, element) in numbers.iter().enumerate() {
println!("numbers[{}] = {}", i, element);
}
}
Multi-dimensional Arrays
rust// 2D array (matrix)
let matrix: [[i32; 3]; 3] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Accessing elements
println!("Element at [1][2]: {}", matrix[1][2]); // 6
// Nested loops for 2D array
for row in &matrix {
for element in row {
print!("{} ", element);
}
println!();
}
// 3D array
let cube: [[[i32; 2]; 2]; 2] = [
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
];
println!("Element at [1][0][1]: {}", cube[1][0][1]); // 6
Array Methods and Operations
rustlet arr = [1, 2, 3, 4, 5];
// Slicing arrays
let slice = &arr[1..4]; // [2, 3, 4]
println!("Slice: {:?}", slice);
// Array patterns in match
match arr {
[1, 2, 3, 4, 5] => println!("Exact match!"),
[first, .., last] => println!("First: {}, Last: {}", first, last),
}
// Converting to slices
let slice_ref: &[i32] = &arr;
println!("Slice length: {}", slice_ref.len());
// Array bounds checking
// This would panic at runtime:
// println!("{}", arr[10]);
// Safe access with get()
if let Some(element) = arr.get(2) {
println!("Element at index 2: {}", element); // 3
}
if let None = arr.get(10) {
println!("Index 10 is out of bounds");
}
Array Limitations and Alternatives
rust// Arrays have fixed size determined at compile time
// This won't work:
// let size = 5;
// let arr = [0; size]; // Error: size must be constant
// Use Vec for dynamic arrays
use std::convert::TryInto;
// Converting between arrays and vectors
let vec = vec![1, 2, 3, 4, 5];
// Convert Vec to array (if you know the size)
let array: [i32; 5] = vec.try_into().unwrap_or_else(|v: Vec<i32>| panic!("Expected length 5, got {}", v.len()));
// Array from function
fn create_array() -> [i32; 3] {
[1, 2, 3] // Return type must match exactly
}
Common Pitfalls
- Array indices start at 0, not 1
- Array size must be known at compile time
- Index out of bounds causes panic at runtime
- Arrays are different types if they have different sizes
- Cannot return arrays from functions that have different sizes
Robust software engineering in Rust relies on tightly integrated unit tests, living documentation tests, and statistically rigorous micro-benchmarks via Criterion.
Unit and Integration Testing
Rust features built-in test runners configured via cargo. Unit tests reside in the same file as implementation code inside a tests module annotated with #[cfg(test)], ensuring they are excluded from production binaries.
rustpub fn divide(a: i32, b: i32) -> Result<i32, &'static str> {
if b == 0 {
return Err("Division by zero");
}
Ok(a / b)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_divide_success() {
assert_eq!(divide(10, 2), Ok(5));
}
#[test]
#[should_panic(expected = "Division by zero")]
fn test_divide_by_zero_panic() {
// Demonstrating panic assertions if unwrap is used
let _ = divide(10, 0).unwrap();
}
}
Integration tests sit in a separate tests/ directory at the crate root, treating your library as an external consumer.
Documentation Tests (Doctests)
Rust uniquely compiles and executes code blocks embedded within documentation comments (///), guaranteeing your code examples never go out of date.
rust/// Calculates the arithmetic mean of two integers.
///
/// # Examples
///
/// ```
/// use old_lane_17::mean;
///
/// let result = mean(4, 6);
/// assert_eq!(result, 5);
/// ```
pub fn mean(a: i32, b: i32) -> i32 {
(a + b) / 2
}
Run both unit tests and doctests simultaneously using cargo test.
High-Precision Benchmarking with Criterion
Built-in cargo bench relies on unstable nightly features. For stable, statistically sound benchmarking against micro-regressions, use the criterion crate.
First, configure your Cargo.toml:
toml[dev-dependencies]
criterion = "0.5"
[[bench]]
name = "my_benchmark"
harness = false
Next, implement the benchmark suite in benches/my_benchmark.rs:
rustuse criterion::{black_box, criterion_group, criterion_main, Criterion};
fn fibonacci(n: u64) -> u64 {
match n {
0 => 0,
1 => 1,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}
fn bench_fibonacci(c: &mut Criterion) {
c.bench_function("fib 20", |b| {
// black_box prevents the compiler from optimizing away pure functions
b.iter(|| fibonacci(black_box(20)))
});
}
criterion_group!(benches, bench_fibonacci);
criterion_main!(benches);
Execute your benchmarks with cargo bench. Criterion measures execution times, calculates confidence intervals, and flags performance regressions.
Gotchas and Performance Considerations
- Compiler Optimization: Always wrap input arguments in
black_box()within benchmarks. Otherwise, Rust’s aggressive dead-code elimination and constant folding will compute results at compile time, rendering benchmark metrics useless. - Doctest Scope: Doctests require explicit imports of your crate name (e.g.,
use my_crate::function;) because each code block compiles as a separate mini-crate. - Shared State: Unit tests run concurrently by default. Avoid mutating global static variables across tests without synchronization primitives like
MutexorOnceLock.
Key Takeaways
- Place unit tests inside
mod testsblocks annotated with#[cfg(test)]directly alongside your code. - Use
///documentation blocks containing runnable code examples to keep public APIs strictly documented and verified. - Leverage
criterionwithblack_boxfor deterministic, regression-proof performance tracking in production codebases.
Array Indexing in Rust
Array indexing allows access to individual elements in an array using their position. Rust uses zero-based indexing and provides bounds checking for safety.
Basic Array Indexing
rustfn main() {
let numbers = [10, 20, 30, 40, 50];
// Accessing elements by index
println!("numbers[0] = {}", numbers[0]); // First element: 10
println!("numbers[2] = {}", numbers[2]); // Third element: 30
println!("numbers[4] = {}", numbers[4]); // Last element: 50
// Modifying elements (array must be mutable)
let mut mutable_numbers = [10, 20, 30, 40, 50];
mutable_numbers[1] = 25; // Change second element from 20 to 25
mutable_numbers[3] = 45; // Change fourth element from 40 to 45
// Display modified array
for (i, &value) in mutable_numbers.iter().enumerate() {
println!("numbers[{}] = {}", i, value);
}
}
Bounds Checking and Safe Access
rustlet arr = [1, 2, 3, 4, 5];
// Unsafe indexing (panics if out of bounds)
// println!("{}", arr[10]); // This would panic!
// Safe indexing with get()
match arr.get(2) {
Some(&value) => println!("Element at index 2: {}", value), // 3
None => println!("Index 2 is out of bounds"),
}
match arr.get(10) {
Some(&value) => println!("Element at index 10: {}", value),
None => println!("Index 10 is out of bounds"), // This executes
}
// Using get() with if let
if let Some(&value) = arr.get(1) {
println!("Second element: {}", value); // 2
}
// Using get_mut() for mutable access
let mut mutable_arr = [1, 2, 3];
if let Some(element) = mutable_arr.get_mut(1) {
*element = 100; // Modify through mutable reference
}
println!("Modified: {:?}", mutable_arr); // [1, 100, 3]
Array Slicing
rustlet numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
// Creating slices
let full_slice = &numbers[..]; // Entire array
let start_slice = &numbers[3..]; // From index 3 to end: [3, 4, 5, 6, 7, 8, 9]
let end_slice = &numbers[..5]; // From start to index 4: [0, 1, 2, 3, 4]
let middle_slice = &numbers[2..7]; // From index 2 to 6: [2, 3, 4, 5, 6]
let exclusive_end = &numbers[2..=6]; // From index 2 to 6 inclusive: [2, 3, 4, 5, 6]
println!("Full: {:?}", full_slice);
println!("Start from 3: {:?}", start_slice);
println!("Up to 5: {:?}", end_slice);
println!("Middle 2..7: {:?}", middle_slice);
// Slices are references and don't own the data
// This allows multiple read-only accesses
let slice1 = &numbers[0..3];
let slice2 = &numbers[3..6];
println!("Slice1: {:?}, Slice2: {:?}", slice1, slice2);
Pattern Matching with Arrays
rustlet point = [10, 20];
// Destructuring arrays
let [x, y] = point;
println!("x: {}, y: {}", x, y); // x: 10, y: 20
// Pattern matching in match statements
match point {
[0, 0] => println!("Origin"),
[x, 0] => println!("On x-axis at {}", x),
[0, y] => println!("On y-axis at {}", y),
[x, y] => println!("At ({}, {})", x, y),
}
// Using .. to ignore parts of the array
let larger = [1, 2, 3, 4, 5];
match larger {
[first, .., last] => println!("First: {}, Last: {}", first, last), // 1, 5
_ => println!("Other pattern"),
}
// Matching specific patterns
let coords = [[1, 2], [3, 4], [5, 6]];
for &[x, y] in &coords {
println!("Coordinate: ({}, {})", x, y);
}
Common Pitfalls
- Accessing out-of-bounds indices causes panic at runtime
- Array indices start at 0, not 1
- Slicing beyond array bounds causes panic
- Forgetting that slices are references, not owned data
Rust’s type system guarantees memory safety, but low-level systems programming requires bypassing these checks via the unsafe keyword and raw pointers. This chapter explores how to safely encapsulate unsafe operations and interface with Foreign Function Interfaces (FFI).
The 'unsafe' Superpower and Raw Pointers
The unsafe keyword does not turn off the borrow checker; it merely unlocks five specific superpowers: dereferencing raw pointers, calling unsafe functions or methods, implementing unsafe traits, mutating mutable static state, and accessing fields of a union.
Raw pointers (*const T and *mut T) bypass all Rust aliasing and lifetime rules. Unlike references (&T and &mut T), they do not have to be aligned, can be null, and do not guarantee valid memory points.
rustfn main() {
let mut num: i32 = 42;
// Creating raw pointers is safe; dereferencing them is unsafe.
let r1: *const i32 = &num as *const i32;
let r2: *mut i32 = &mut num as *mut i32;
unsafe {
println!("r1 points to: {}", *r1);
// Mutating through a raw pointer
*r2 = 100;
println!("r2 modified value to: {}", *r2);
}
}
Creating Safe Abstractions over Unsafe Code
Idiomatic Rust encapsulates unsafe operations inside safe APIs. Callers should never have to write unsafe blocks just to use a well-designed data structure.
rustuse std::slice;
// A safe function wrapping an unsafe pointer operation to create a slice.
fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = slice.len();
let ptr = slice.as_mut_ptr();
assert!(mid <= len);
unsafe {
(
slice::from_raw_parts_mut(ptr, mid),
slice::from_raw_parts_mut(ptr.add(mid), len - mid),
)
}
}
fn main() {
let mut data = [1, 2, 3, 4, 5];
let (left, right) = split_at_mut(&mut data, 2);
left[0] = 99;
println!("{:?}", right); // [3, 4, 5]
println!("{:?}", left); // [99, 2]
}
Interfacing with C via Foreign Function Interfaces (FFI)
Rust guarantees ABI compatibility with C. We can link external C libraries or expose Rust functions to C by disabling name mangling with #[no_mangle] and specifying the calling convention via extern "C".
rust// Declaring an external C function (e.g., from libc)
extern "C" {
fn abs(input: i32) -> i32;
}
// Exposing a Rust function to be called from C
#[no_mangle]
pub extern "C" fn rust_add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
unsafe {
// Calling an external C function requires an unsafe block
let absolute_value = abs(-42);
println!("Absolute value from C abs(): {}", absolute_value);
}
}
Expected Output
textr1 points to: 42
r2 modified value to: 100
[3, 4, 5]
[99, 2]
Absolute value from C abs(): 42
Common Gotchas and Best Practices
- Undefined Behavior (UB): Creating a reference from a raw pointer (
&*ptr) instantly enforces Rust’s aliasing rules. If the underlying data violates these rules (e.g., aliasing mutable references), it causes UB. - Null Checks: Always check if a raw pointer is null before dereferencing, especially when dealing with C APIs.
- Minimizing Unsafe Scope: Keep
unsafeblocks as small as possible. Never make an entire functionunsafewhen only a single pointer offset requires it.
Key Takeaways
unsafegrants permission to dereference raw pointers, call foreign functions, and mutate statics—it does not disable the borrow checker.- Raw pointers (
*const T,*mut T) do not enforce borrowing or lifetime guarantees. - Wrap unsafe internals inside safe APIs to maintain ergonomic and memory-safe abstractions for library consumers.
- Use
#[no_mangle]andextern "C"to interoperate seamlessly with C codebases.
Rust’s async/await syntax sugar compiles down to state machines implementing the low-level Future trait, which drives non-blocking concurrency atop runtimes like Tokio. Mastering advanced async requires manually implementing futures, understanding task wakes, and managing execution boundaries.
The Anatomy of the Future Trait
At its core, a Future in Rust is not a background thread; it is a lazy computation state machine. The trait is defined in core::future::Future as follows:
rustuse std::pin::Pin;
use std::task::{Context, Poll};
pub trait Future {
type Output;
fn poll(self: Pin<&Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
The runtime repeatedly calls poll until it returns Poll::Ready(output). If the resource is not ready, the future returns Poll::Pending and registers a Waker from the Context to notify the runtime when to poll it again.
Writing a Custom Non-Blocking Future
To build a custom future, we must implement state tracking and handle pinning correctly. Below is a custom future that yields a value after being polled a specific number of times, simulating an asynchronous tick or non-blocking I/O readiness check.
rustuse std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::time::Instant;
struct DelayTimer {
expiry: Instant,
duration: Duration,
}
impl DelayTimer {
fn new(duration: Duration) -> Self {
Self {
expiry: Instant::now() + duration,
duration,
}
}
}
impl Future for DelayTimer {
type Output = &'static str;
fn poll(self: Pin<&Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if Instant::now() >= self.expiry {
Poll::Ready("Timer expired successfully!")
} else {
// In a real I/O driver, we register the current task waker with an OS selector (epoll/kqueue).
// Here we use a standard thread-sleep waker trigger for demonstration.
let waker = cx.waker().clone();
let expiry = self.expiry;
std::thread::spawn(move || {
let remaining = expiry.saturating_duration_since(Instant::now());
std::thread::sleep(remaining);
waker.wake();
});
Poll::Pending
}
}
}
#[tokio::main]
async fn main() {
println!("Starting custom future...");
let timer = DelayTimer::new(Duration::from_millis(500));
let result = timer.await;
println!("{}", result);
}
Pinning and Unpin
Because futures can contain self-referential pointers (where a field points to another field inside the same struct), moving them in memory after polling breaks memory safety. Rust uses Pin<Ptr<T>> to guarantee that a value will not be moved in memory.
Most types implement Unpin, meaning they can be moved safely even after being polled. Types that contain references to themselves do not implement Unpin and must be explicitly pinned using Box::pin() or stack pinning macros.
rustuse std::pin::Pin;
use std::future::Future;
fn process_future<F>(f: F)
where
F: Future<Output = ()> + Unpin,
{
// If F is Unpin, we don't need explicit pinning gymnastics.
}
// For non-Unpin futures (e.g., self-referential async blocks), wrap in Pin:
async fn run_pinned() {
let fut = async { /* ... */ };
let pinned_fut = Box::pin(fut);
// Now pinned_fut can be driven manually or passed to APIs requiring Pin
}
Integrating with Tokio Runtimes
Tokio manages an MPMC (Multi-Producer, Multi-Consumer) work-stealing thread pool. When integrating low-level networking or system calls with Tokio, use tokio::io::AsyncRead and tokio::io::AsyncWrite, or bridge blocking synchronous code via tokio::task::spawn_blocking.
rust#[tokio::main]
async fn main() {
// Offloading CPU-heavy or blocking synchronous operations safely
let heavy_computation = tokio::task::spawn_blocking(|| {
// Perform synchronous blocking file I/O or heavy math here
"Computation Complete"
});
match heavy_computation.await {
Ok(res) => println!("{}", res),
Err(e) => eprintln!("Task failed: {}", e),
}
}
Expected Output
textStarting custom future...
Timer expired successfully!
Computation Complete
Gotchas and Performance Considerations
- Spurious Wake-ups: Always design your custom
pollimplementation to re-verify readiness conditions. AWakercan be called spuriously even if the underlying resource is not ready. - Blocking the Executor: Never run synchronous, blocking loops (
std::thread::sleep, heavy blocking I/O) directly inside anasync fnexecuted on an async runtime. This starves the worker thread and halts other tasks. Usespawn_blockinginstead. - Overusing Boxes: Pinning via
Box::pinincurs a heap allocation. Prefer stack pinning viatokio::pin!macro when performance is critical.
Key Takeaways
- Futures are state machines evaluated lazily via the
pollmethod, returning eitherPoll::ReadyorPoll::Pending. - The
Wakermechanism allows runtimes to sleep tasks and awaken them precisely when external resources (network sockets, timers) become available. Pinensures memory safety for self-referential async state machines by preventing relocation in memory.- Tokio provides work-stealing thread pools and utilities like
spawn_blockingto bridge synchronous and asynchronous paradigms seamlessly.
Array Functions and Methods in Rust
While Rust arrays have a fixed size and limited built-in methods, there are many ways to work with arrays using standard library functions, iterators, and conversions.
Array Utilities and Conversions
rustfn main() {
let numbers = [5, 2, 8, 1, 9, 3];
// Array length
println!("Array length: {}", numbers.len());
// Check if empty (arrays are never empty if size > 0)
println!("Is empty: {}", numbers.is_empty()); // false
// First and last elements
println!("First: {:?}", numbers.first()); // Some(5)
println!("Last: {:?}", numbers.last()); // Some(3)
// Converting to slices (most array methods work on slices)
let slice: &[i32] = &numbers;
println!("Slice length: {}", slice.len());
}
Working with Array Iterators
rustlet numbers = [1, 2, 3, 4, 5];
// Basic iteration
println!("Elements:");
for num in &numbers {
println!("{}", num);
}
// Using iterator methods
let sum: i32 = numbers.iter().sum();
println!("Sum: {}", sum); // 15
let doubled: Vec<i32> = numbers.iter().map(|&x| x * 2).collect();
println!("Doubled: {:?}", doubled); // [2, 4, 6, 8, 10]
// Filtering
let evens: Vec<&i32> = numbers.iter().filter(|&&x| x % 2 == 0).collect();
println!("Evens: {:?}", evens); // [2, 4]
// Finding elements
if let Some(&value) = numbers.iter().find(|&&x| x == 3) {
println!("Found 3 at some position");
}
// Position of element
if let Some(pos) = numbers.iter().position(|&x| x == 4) {
println!("4 found at position: {}", pos); // 3
}
Array Manipulation Techniques
rust// Since arrays are fixed-size, we often work with slices or convert to Vec
// Sorting (this consumes the array and returns a new one)
let mut unsorted = [5, 2, 8, 1, 9];
unsorted.sort();
println!("Sorted: {:?}", unsorted); // [1, 2, 5, 8, 9]
// Reverse
unsorted.reverse();
println!("Reversed: {:?}", unsorted); // [9, 8, 5, 2, 1]
// Fill array with value
let mut arr = [0; 5];
arr.fill(42);
println!("Filled: {:?}", arr); // [42, 42, 42, 42, 42]
// Windows and chunks (working with slices)
let data = [1, 2, 3, 4, 5, 6];
for window in data.windows(3) {
println!("Window: {:?}", window); // [1,2,3], [2,3,4], [3,4,5], [4,5,6]
}
for chunk in data.chunks(2) {
println!("Chunk: {:?}", chunk); // [1,2], [3,4], [5,6]
}
Array Conversions
rustuse std::convert::TryInto;
// Converting between arrays and other types
let vec = vec![1, 2, 3, 4, 5];
// Vec to array (must know exact size)
let array: [i32; 5] = match vec.try_into() {
Ok(arr) => arr,
Err(_) => panic!("Cannot convert Vec to array - wrong size"),
};
// Array to Vec
let back_to_vec = array.to_vec();
println!("Back to Vec: {:?}", back_to_vec);
// TryFrom conversion (more idiomatic)
let another_array: [i32; 5] = vec.try_into().expect("Wrong size");
// Converting between different array sizes
let small = [1, 2, 3];
// This doesn't work directly:
// let large: [i32; 5] = small; // Error
// Manual conversion
let mut large = [0; 5];
large[..3].copy_from_slice(&small);
println!("Extended: {:?}", large); // [1, 2, 3, 0, 0]
Multi-dimensional Array Operations
rustlet matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Flattening 2D array
let flattened: Vec<i32> = matrix.iter().flatten().cloned().collect();
println!("Flattened: {:?}", flattened); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
// Transpose (manual implementation)
let mut transpose = [[0; 3]; 3];
for i in 0..3 {
for j in 0..3 {
transpose[j][i] = matrix[i][j];
}
}
println!("Transpose: {:?}", transpose); // [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
// Working with rows and columns
for (i, row) in matrix.iter().enumerate() {
println!("Row {}: {:?}", i, row);
}
// Column iteration (more complex)
for col in 0..3 {
let column: Vec<i32> = matrix.iter().map(|row| row[col]).collect();
println!("Column {}: {:?}", col, column);
}
Common Pitfalls
- Arrays don't have many built-in methods - use slices or iterators
- Cannot resize arrays - use Vec for dynamic sizing
- Array conversions require exact size matching
- Multi-dimensional array operations often require manual loops
Procedural macros transform Rust syntax trees (TokenStream to TokenStream) at compile time, empowering you to generate boilerplate code safely and efficiently. This tutorial dives into authoring custom derive attributes and handling token manipulation using the syn and quote crates.
The Procedural Macro Architecture
Rust enforces a strict compilation boundary for procedural macros: they must reside in a dedicated crate with proc-macro = true set in its Cargo.toml. This separation exists because the macro code itself must be compiled to a dynamic library and executed by the compiler during the build phase of your primary crate.
Set up your macro crate’s Cargo.toml:
toml[package]
name = "orm_derive"
version = "0.1.0"
edition = "2021"
[lib]
proc-macro = true
[dependencies]
syn = { version = "2.0", features = ["full"] }
quote = "1.0"
proc-macro2 = "1.0"
Building a Custom Derive Macro
We will build a custom derive macro named Model that inspects a struct and generates a helper method returning its SQL table name based on the struct identifier.
rust// orm_derive/src/lib.rs
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Model)]
pub fn derive_model(input: TokenStream) -> TokenStream {
// Parse the token stream into a syntax tree representing a struct/enum declaration
let input = parse_macro_input!(input as DeriveInput);
// Extract the name of the struct
let name = &input.ident;
// Convert the struct name to a lowercase string for the table name
let table_name = name.to_string().to_lowercase();
// Generate expansion using the quote! macro
let expanded = quote! {
impl #name {
pub fn table_name() -> &'static str {
#table_name
}
}
};
// Return the generated token stream
expanded.into()
}
Handling Struct Fields and Attributes
Real-world macros frequently need to inspect struct fields to generate serialization or mapping logic. Below is an extension that iterates over named fields to generate a dynamic column inspector.
rust#[proc_macro_derive(Inspector)]
pub fn derive_inspector(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
// Match on data structures to ensure we only implement for structs with named fields
let fields = match &input.data {
syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(fields),
..
}) => &fields.named,
_ => panic!("Inspector only supports structs with named fields"),
};
// Map each field identifier to a string representation
let field_names = fields.iter().map(|f| {
let name = f.ident.as_ref().unwrap();
name.to_string()
});
let expanded = quote! {
impl #name {
pub fn columns() -> Vec<&'static str> {
vec![#(#field_names),*]
}
}
};
expanded.into()
}
Notice the repetition operator #(#field_names),*. This is quote! syntax for repeating the tokens inside the parentheses, separated by commas, mirroring Rust’s macro expansion patterns.
Consuming the Procedural Macro
To use your custom derive macro, consume the orm_derive crate in a separate binary or library crate.
rust// main.rs
use orm_derive::{Model, Inspector};
#[derive(Model, Inspector)]
struct User {
id: u64,
username: String,
email: String,
}
fn main() {
println!("Table: {}", User::table_name());
println!("Columns: {:?}", User::columns());
}
Expected Output:
textTable: user
Columns: ["id", "username", "email"]
Gotchas and Performance Considerations
- Compilation Overhead: Procedural macro crates compile before your main crate logic and depend on heavy parsing infrastructure (
syn,quote). Keep macro logic focused to minimize build bottlenecks. - Span Hygiene: Use
proc-macro2for internal logic so your code remains testable outside of the compiler’s nativeproc_macroenvironment. - Error Messages: Avoid raw
panic!calls where possible when parsing fails. Instead, returnsyn::Error::to_compile_error()token streams to emit precise underlines directly in the user’s IDE/compiler output.
Key Takeaways
- Procedural macro crates require
proc-macro = truein their configuration and must be compiled as dynamic libraries. - The
syncrate parses rawTokenStreaminput into robust, type-checked Abstract Syntax Trees (ASTs). - The
quote!macro utilizes interpolation (#var) and repetition (#(...),*) to synthesize clean, idiomatic Rust code structures safely.
Vectors in Rust
Vectors (Vec<T>) are growable arrays that can dynamically resize. They are heap-allocated and one of the most commonly used data structures in Rust.
Creating and Using Vectors
rustfn main() {
// Different ways to create vectors
let numbers: Vec<i32> = Vec::new(); // Empty vector
let mut primes = vec![2, 3, 5, 7, 11]; // Initialized with macro
let zeros = vec![0; 5]; // 5 elements, all 0
// Adding elements
primes.push(13); // Add to end
primes.insert(2, 4); // Insert at index 2
// Accessing elements
println!("First: {}", primes[0]); // 2
println!("Second: {}", primes.get(1).unwrap()); // 3 (safe access)
// Size and capacity
println!("Length: {}", primes.len()); // 7
println!("Capacity: {}", primes.capacity()); // Current capacity
println!("Is empty: {}", primes.is_empty()); // false
// Reserve capacity
primes.reserve(10);
println!("New capacity: {}", primes.capacity());
// Remove elements
let removed = primes.remove(2); // Remove element at index 2
let popped = primes.pop(); // Remove last element
println!("Removed: {}, Popped: {:?}", removed, popped);
println!("Final vector: {:?}", primes);
}
Vector Operations
rustlet mut vec = vec![1, 2, 3, 4, 5];
// Iterating
println!("Elements:");
for i in 0..vec.len() {
println!("vec[{}] = {}", i, vec[i]);
}
// Better: using iterators (borrowed)
println!("Using iterator:");
for element in &vec {
println!("Element: {}", element);
}
// Mutable iteration
for element in &mut vec {
*element *= 2; // Double each element
}
println!("Doubled: {:?}", vec); // [2, 4, 6, 8, 10]
// Range-based for loop with values (consumes vector)
// for element in vec { ... } // This would move vec
// Useful vector methods
vec.clear(); // Remove all elements
vec.extend([1, 2, 3].iter().copied()); // Add multiple elements
vec.truncate(2); // Truncate to first 2 elements
vec.shrink_to_fit(); // Reduce capacity to fit current size
println!("After operations: {:?}", vec);
Vector vs Array
rust// Arrays: Fixed size, stack allocation
let arr = [1, 2, 3, 4, 5];
// arr.push(6); // Error - fixed size
// Vectors: Dynamic size, heap allocation
let mut vec = vec![1, 2, 3, 4, 5];
vec.push(6); // OK - can grow
vec.pop(); // Remove last element
// Converting between arrays and vectors
let array = [1, 2, 3];
let vector = array.to_vec(); // Array to Vec
let from_vec: Vec<i32> = vec![4, 5, 6];
// Try to convert Vec to array (must be exact size)
if let Ok(array_back) = from_vec.try_into() {
let arr: [i32; 3] = array_back;
println!("Back to array: {:?}", arr);
}
Advanced Vector Usage
rust// Vector of different types using enums
#[derive(Debug)]
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Float(10.12),
SpreadsheetCell::Text(String::from("blue")),
];
println!("Row: {:?}", row);
// Splitting vectors
let mut numbers = vec![1, 2, 3, 4, 5, 6];
let second_half = numbers.split_off(3); // numbers now has [1,2,3], second_half has [4,5,6]
println!("First: {:?}, Second: {:?}", numbers, second_half);
// Drain elements (remove range and get iterator)
let mut data = vec![1, 2, 3, 4, 5];
let drained: Vec<i32> = data.drain(1..4).collect(); // data becomes [1,5]
println!("Drained: {:?}, Remaining: {:?}", drained, data);
// Retain elements matching condition
let mut values = vec![1, 2, 3, 4, 5, 6];
values.retain(|&x| x % 2 == 0); // Keep only even numbers
println!("Even values: {:?}", values); // [2, 4, 6]
Vector Performance Considerations
rust// Pre-allocate capacity when size is known
let mut large_vec = Vec::with_capacity(1000);
for i in 0..1000 {
large_vec.push(i);
}
// This avoids repeated reallocations
println!("Length: {}, Capacity: {}", large_vec.len(), large_vec.capacity());
// Collect from iterator with size hint
let collected: Vec<i32> = (0..1000).collect();
println!("Collected length: {}", collected.len());
// Using into_iter() vs iter()
let vec1 = vec![1, 2, 3];
// This consumes vec1:
// for element in vec1.into_iter() { ... }
// This borrows vec1:
for element in vec1.iter() {
println!("{}", element);
}
// vec1 is still usable here
Common Pitfalls
- Accessing elements with
[]can panic if index is out of bounds - Use
get()for bounds-checked access - Vectors can be less efficient than arrays for very small, fixed-size data
- Inserting/erasing in the middle is O(n) operation
- Forgetting that some operations consume the vector
Rust’s strict type system and ownership model enable zero-cost architectural patterns that enforce decoupling, thread safety, and maintainability at compile time. This chapter explores how to design modular library crates using dependency injection, sealed traits, and structured telemetry.
Modular Crate Design and the Facade Pattern
A scalable library crate avoids exposing flat, tightly coupled modules. Instead, it exposes a minimal public API surface via a facade struct while hiding internal execution engines in private sub-modules.
rust// src/lib.rs
pub mod engine;
pub mod telemetry;
// Re-export the primary facade and core domain types
pub use engine::{Engine, EngineConfig};
pub use telemetry::{Event, Logger};
The facade delegates work to specialized internal components, preventing downstream users from depending on implementation details.
rust// src/engine.rs
use crate::telemetry::Logger;
#[derive(Debug, Clone)]
pub struct EngineConfig {
pub worker_threads: usize,
}
pub struct Engine<L: Logger> {
config: EngineConfig,
logger: L,
}
impl<L: Logger> Engine<L> {
pub fn new(config: EngineConfig, logger: L) -> Self {
logger.log("Initializing core engine architecture.");
Self { config, logger }
}
pub fn execute(&self, task_name: &str) {
self.logger.log(&format!("Executing task: {} on {} threads", task_name, self.config.worker_threads));
}
}
Zero-Cost Dependency Injection via Generics
Instead of dynamic dispatch (Box<dyn Trait>), which incurs vtable overhead and prevents compiler optimizations, use generic trait bounds. This allows the compiler to monomorphize the code, completely eliminating abstraction penalties.
rust// src/telemetry.rs
pub trait Logger: Send + Sync + 'static {
fn log(&self, message: &str);
}
// A concrete implementation for production use
#[derive(Clone, Copy)]
pub struct StdoutLogger;
impl Logger for StdoutLogger {
fn log(&self, message: &str) {
// In a real system, integrate with structured logging like tracing
println!("[INFO] {message}");
}
}
By accepting L: Logger rather than &dyn Logger, the compiler inlines calls to log, rendering the abstraction literally free.
Sealed Traits for Safe API Extensions
When designing libraries, you often want to implement a trait across internal types while preventing external users from implementing it downstream. The “Sealed Trait” idiom solves this by leveraging a private supertrait.
rust// src/storage.rs
mod sealed {
pub trait Sealed {}
}
// Public trait requires private sealed::Sealed, blocking external implementations
pub trait Storable: sealed::Sealed {
fn serialize(&self) -> Vec<u8>;
}
pub struct Record {
pub id: u64,
}
// Allowed because Record is in the same crate
impl sealed::Sealed for Record {}
impl Storable for Record {
fn serialize(&self) -> Vec<u8> {
self.id.to_ne_bytes().to_vec()
}
}
Putting It Together: Application Entry Point
rust// src/main.rs
use rust_architecture::{Engine, EngineConfig, StdoutLogger};
fn main() {
let config = EngineConfig { worker_threads: 4 };
let logger = StdoutLogger;
let engine = Engine::new(config, logger);
engine.execute("DataIngestion");
}
Expected Terminal Output
```text [INFO] Initializing core engine architecture. [INFO] Executing task: DataIngestion on 4 threads ```Performance Considerations and Edge Cases
- Monomorphization Bloat: Heavy use of generics can cause code bloat (binary size increase). Use dynamic dispatch (`Box
`) only when hot paths are not impacted and binary size or compilation times are a primary constraint. - Send + Sync Bounds: Always bound architectural traits with `Send + Sync + 'static` if your types will cross thread boundaries, preventing subtle concurrency bugs at compile time.
Key Takeaways
- Keep public crate interfaces minimal by utilizing re-exports and internal sub-modules.
- Prefer generic trait bounds over trait objects (`dyn Trait`) to secure zero-cost abstractions through monomorphization.
- Use sealed traits to maintain control over trait implementations and prevent downstream breaking changes.
- Inject dependencies (like loggers or storage engines) rather than relying on global singletons, drastically improving testability.
References in Rust
References are non-owning pointers that allow you to access data without taking ownership. Rust's reference system is central to its memory safety guarantees.
Basic Reference Operations
rustfn main() {
let number = 42;
let number_ref = &number; // Immutable reference
println!("Value: {}", number);
println!("Address: {:p}", number_ref);
println!("Value through reference: {}", *number_ref); // Dereferencing
// Mutable references
let mut mutable_number = 100;
let mutable_ref = &mut mutable_number;
*mutable_ref += 50; // Modify through mutable reference
println!("Modified value: {}", mutable_number); // 150
// References in functions
let text = String::from("Hello");
let length = calculate_length(&text); // Pass reference, not ownership
println!("Length of '{}': {}", text, length); // text still usable here
}
fn calculate_length(s: &String) -> usize {
s.len()
} // s goes out of scope, but since it's a reference, nothing is dropped
Reference Rules and Limitations
rustlet mut data = String::from("Hello");
// Multiple immutable references are allowed
let ref1 = &data;
let ref2 = &data;
println!("{}, {}", ref1, ref2); // Both can be used
// But only one mutable reference at a time
let mut_ref1 = &mut data;
// let mut_ref2 = &mut data; // This would cause compile error!
println!("{}", mut_ref1);
// Cannot mix mutable and immutable references
// let immutable_ref = &data; // This would error
// let mutable_ref = &mut data; // if this exists
// References must always be valid
fn dangling_reference_example() {
// This function would not compile:
// let reference = dangle(); // Error: returns reference to dropped value
}
// fn dangle() -> &String {
// let s = String::from("hello");
// &s // s is dropped here, so reference would be invalid
// }
Working with References in Data Structures
rust// Struct with references require lifetimes
#[derive(Debug)]
struct Book<'a> {
title: &'a str,
author: &'a str,
}
fn main() {
let title = "The Rust Programming Language";
let author = "Steve Klabnik and Carol Nichols";
let book = Book { title, author };
println!("Book: {:?}", book);
// References in collections
let strings = vec!["hello", "world"];
let string_refs: Vec<&str> = strings.iter().map(|s| *s).collect();
println!("String refs: {:?}", string_refs);
// Reference to slice
let array = [1, 2, 3, 4, 5];
let slice_ref = &array[1..4]; // Reference to part of array
println!("Slice: {:?}", slice_ref); // [2, 3, 4]
}
Reference Patterns and Destructuring
rustlet point = (10, 20);
// Pattern matching with references
match &point {
(x, y) => println!("Point at ({}, {})", x, y), // x and y are &i32
}
// Destructuring references
let &(x, y) = &point;
println!("x: {}, y: {}", x, y);
// Reference patterns in function parameters
fn print_coordinates(&(x, y): &(i32, i32)) {
println!("Current location: ({}, {})", x, y);
}
print_coordinates(&point);
// Using ref in patterns (less common in modern Rust)
let maybe_value = Some(42);
if let Some(ref value) = maybe_value {
println!("Got a reference to: {}", value); // value is &i32
}
Common Pitfalls
- Trying to create multiple mutable references to the same data
- Mixing mutable and immutable references
- Returning references to local variables (dangling references)
- Forgetting that references have lifetime constraints
- Confusing
&Twith&mut Tin function signatures
Borrowing in Rust
Borrowing is Rust's mechanism for allowing temporary access to data without transferring ownership. The borrow checker enforces rules at compile time to prevent data races and memory errors.
Borrowing Rules
rustfn main() {
let mut s = String::from("hello");
// Rule 1: Any number of immutable borrows
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2);
// r1 and r2 are no longer used after this point
// Rule 2: Only one mutable borrow in scope
let r3 = &mut s;
// println!("{}", r1); // This would error - can't use r1 while r3 exists
r3.push_str(", world");
println!("{}", r3);
// Rule 3: Cannot mix mutable and immutable borrows
// let r4 = &s; // This would error
// let r5 = &mut s; // if both exist
demonstrate_scope();
}
fn demonstrate_scope() {
let mut data = String::from("test");
{
let borrow1 = &data; // First immutable borrow
println!("First borrow: {}", borrow1);
} // borrow1 goes out of scope here
// Now we can borrow mutably because no other references exist
let borrow2 = &mut data;
borrow2.push_str(" modified");
println!("After mutable borrow: {}", borrow2);
}
Function Parameters and Borrowing
rust// Functions that borrow vs take ownership
fn take_ownership(s: String) -> String {
println!("I own: {}", s);
s // Return ownership
}
fn borrow_readonly(s: &String) {
println!("I can read: {}", s);
// s.push_str("!"); // Error - s is immutable reference
}
fn borrow_mutable(s: &mut String) {
s.push_str("!");
println!("I modified: {}", s);
}
fn main() {
let mut text = String::from("Hello");
borrow_readonly(&text); // Immutable borrow
borrow_mutable(&mut text); // Mutable borrow
println!("After functions: {}", text); // text still owned here
let returned = take_ownership(text); // Ownership transferred
// println!("{}", text); // Error - text was moved
println!("Returned: {}", returned);
}
Borrowing with Collections
rustfn main() {
let mut vec = vec![1, 2, 3, 4, 5];
// Borrowing elements from vector
let first = &vec[0];
// vec.push(6); // This would error - can't mutate while borrowed
println!("First element: {}", first);
// After first is no longer used, we can modify
vec.push(6);
println!("Vector: {:?}", vec);
// Iterators and borrowing
for element in &vec { // Immutable borrow
println!("Element: {}", element);
}
// Mutable iteration
for element in &mut vec { // Mutable borrow
*element *= 2;
}
println!("Doubled: {:?}", vec);
// Using iter() vs into_iter()
let doubled: Vec<i32> = vec.iter().map(|x| x * 2).collect(); // vec still usable
// let consumed: Vec<i32> = vec.into_iter().collect(); // vec consumed
}
Lifetimes and Borrowing
rust// Simple case - compiler can infer lifetimes
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
// Explicit lifetime annotation needed for structs
struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention please: {}", announcement);
self.part
}
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().expect("Could not find a '.'");
let i = ImportantExcerpt {
part: first_sentence,
};
println!("Excerpt: {}", i.part);
}
Common Borrowing Patterns
rust// Returning references from functions
fn get_first_char(s: &String) -> Option<char> {
s.chars().next()
}
// Working with Option<&T>
fn find_number(numbers: &[i32], target: i32) -> Option<&i32> {
numbers.iter().find(|&&x| x == target)
}
// Borrowing in match expressions
fn process_option(opt: &Option<String>) {
match opt {
Some(s) => println!("Got: {}", s), // s is &String
None => println!("Got nothing"),
}
}
// Using RefCell for interior mutability (advanced)
use std::cell::RefCell;
let data = RefCell::new(42);
{
let mut borrow = data.borrow_mut();
*borrow += 1;
}
println!("Data: {}", *data.borrow());
Common Pitfalls
- Trying to mutate a borrowed value without a mutable reference
- Creating dangling references by returning references to local data
- Forgetting that borrowed data cannot be moved while borrowed
- Mixing different kinds of borrows in the same scope
- Not understanding lifetime elision rules
Rust’s Foreign Function Interface (FFI) allows
Rust’s type system can be leveraged beyond simple data validation to enforce complex state machines and invariants entirely at compile time, eliminating invalid runtime states with zero runtime overhead.
The Type-State Pattern
The type-state pattern encodes an object’s lifecycle and valid operations into its type. By consuming self and returning a new type, methods enforce legal state transitions statically.
rustuse std::marker::PhantomData;
// Marker types for states
pub struct Disconnected;
pub struct Connected;
pub struct Authenticated;
pub struct Connection<State> {
endpoint: String,
_marker: PhantomData<State>,
}
impl Connection<Disconnected> {
pub fn new(endpoint: &str) -> Self {
Self {
endpoint: endpoint.to_string(),
_marker: PhantomData,
}
}
pub fn connect(self) -> Connection<Connected> {
println!("Connecting to {}...", self.endpoint);
Connection {
endpoint: self.endpoint,
_marker: PhantomData,
}
}
}
impl Connection<Connected> {
pub fn authenticate(self, token: &str) -> Connection<Authenticated> {
println!("Authenticating with token: {}", token);
Connection {
endpoint: self.endpoint,
_marker: PhantomData,
}
}
pub fn disconnect(self) -> Connection<Disconnected> {
println!("Disconnecting.");
Connection {
endpoint: self.endpoint,
_marker: PhantomData,
}
}
}
impl Connection<Authenticated> {
pub fn send_payload(&self, data: &str) {
println!("Sending payload to {}: {}", self.endpoint, data);
}
}
fn main() {
let conn = Connection::new("127.0.0.1:8080");
let connected = conn.connect();
let authed = connected.authenticate("secret_token");
authed.send_payload("Hello, Type-State!");
// COMPILE ERROR IF UNCOMMENTED:
// conn.send_payload("Fail");
// The Disconnected type does not have `send_payload` method.
}
PhantomData and Zero-Cost Abstractions
PhantomData<T> is a zero-sized type that informs the compiler that a struct acts as if it owns a T, even though it doesn’t. This allows tracking generic parameters that are only used at compile time without storing actual data at runtime.
rustuse std::marker::PhantomData;
pub struct Meters;
pub struct Feet;
pub struct Distance<Unit> {
value: f64,
_unit: PhantomData<Unit>,
}
impl Distance<Meters> {
pub fn new_meters(value: f64) -> Self {
Self { value, _unit: PhantomData }
}
pub fn to_feet(self) -> Distance<Feet> {
Distance {
value: self.value * 3.28084,
_unit: PhantomData,
}
}
}
impl Distance<Feet> {
pub fn value(&self) -> f64 {
self.value
}
}
fn main() {
let m = Distance::<Meters>::new_meters(10.0);
let f = m.to_feet();
println!("Distance in feet: {:.2}", f.value());
}
Expected Output:
textConnecting to 127.0.0.1:8080...
Authenticating with token: secret_token
Sending payload to 127.0.0.1:8080: Hello, Type-State!
Distance in feet: 32.81
Gotchas and Performance Considerations
- Zero Runtime Overhead:
PhantomDatacompiles down to nothing. The compiler drops state tracking types entirely during monomorphization. - Consuming
self: Type-state transitions require takingselfby value. If you need objects to remain usable after a failed transition, return aResult<NewState, (Self, Error)>. - Error Messages: Complex nested type-states can lead to verbose compiler diagnostics. Keep state names descriptive to ease readability.
Key Takeaways
- Compile-Time Guarantees: Invalid API usages (e.g., sending data before authentication) are rejected by the compiler, not at runtime.
PhantomData: Essential for anchoring unused generic parameters to structures safely.- Move Semantics: Consuming
selfduring transitions prevents reuse of old states, enforcing correct lifecycles.
Variables in Rust
Variables in Rust are immutable by default and have move semantics. Understanding variable binding, mutability, and ownership is crucial for writing correct Rust code.
Variable Declaration and Mutability
rustfn main() {
// Immutable by default
let x = 5;
// x = 6; // Error: cannot assign twice to immutable variable
// Mutable variables
let mut y = 10;
y = 15; // This is allowed
println!("y: {}", y);
// Variable shadowing (different from mutability)
let z = 5;
let z = z + 1; // New variable with same name
let z = z * 2; // Another new variable
println!("z: {}", z); // 12
// Shadowing with different type
let spaces = " ";
let spaces = spaces.len(); // This is allowed with shadowing
println!("Spaces: {}", spaces);
// Constants (must have type annotation)
const MAX_POINTS: u32 = 100_000;
println!("Max points: {}", MAX_POINTS);
}
Variable Scope and Ownership
rustfn main() {
// Variable comes into scope
let s = String::from("hello"); // s is valid from this point forward
takes_ownership(s); // s's value moves into the function...
// ... and is no longer valid here
let x = 5; // x comes into scope
makes_copy(x); // x would move into the function,
// but i32 is Copy, so it's okay to still
// use x afterward
// println!("{}", s); // This would error - s was moved
println!("x: {}", x); // This works - x is Copy
} // Here, x goes out of scope, then s. But since s's value was moved, nothing
// special happens.
fn takes_ownership(some_string: String) { // some_string comes into scope
println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) { // some_integer comes into scope
println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
Pattern Matching and Destructuring
rust// Destructuring tuples
let point = (10, 20);
let (x, y) = point;
println!("x: {}, y: {}", x, y);
// Destructuring structs
struct Point {
x: i32,
y: i32,
}
let point = Point { x: 10, y: 20 };
let Point { x: a, y: b } = point;
println!("a: {}, b: {}", a, b);
// Shorthand destructuring (same variable names)
let Point { x, y } = point;
println!("x: {}, y: {}", x, y);
// Pattern matching in let
let some_option = Some(5);
if let Some(value) = some_option {
println!("Got a value: {}", value);
}
// Multiple patterns
let number = 7;
match number {
1 => println!("One"),
2 | 3 | 5 | 7 => println!("Prime"),
_ => println!("Other"),
}
Type Inference and Annotations
rust// Rust has excellent type inference
let x = 5; // Compiler infers i32
let y = 3.14; // Compiler infers f64
let z = "hello"; // Compiler infers &str
// Sometimes explicit types are needed
let collected: Vec<i32> = (0..5).collect();
let parsed: i32 = "42".parse().unwrap();
// Turbofish syntax for explicit types
let numbers = (0..5).collect::<Vec<i32>>();
let float_vec = vec![1.0, 2.0, 3.0f64];
// Type aliases
type Kilometers = i32;
let distance: Kilometers = 100;
println!("Distance: {} km", distance);
Advanced Variable Patterns
rust// Variables in different contexts
fn main() {
// @ bindings in patterns
let value = Some(42);
match value {
Some(x @ 1..=100) => println!("Got small number: {}", x),
Some(x) => println!("Got large number: {}", x),
None => println!("Got nothing"),
}
// Ignoring parts of patterns
let (x, _, z) = (1, 2, 3);
println!("x: {}, z: {}", x, z);
// .. to ignore remaining parts
let numbers = (1, 2, 3, 4, 5);
match numbers {
(first, .., last) => println!("First: {}, Last: {}", first, last),
}
// ref patterns (less common in modern Rust)
let maybe_string = Some(String::from("hello"));
if let Some(ref s) = maybe_string {
println!("s is a reference to: {}", s); // s is &String
}
// maybe_string is still usable here
// ref mut for mutable references
let mut maybe_num = Some(42);
if let Some(ref mut n) = maybe_num {
*n += 1;
}
println!("Maybe num: {:?}", maybe_num); // Some(43)
}
Common Pitfalls
- Forgetting that variables are immutable by default
- Confusing variable shadowing with mutability
- Trying to use moved values after ownership transfer
- Not understanding the difference between Copy and Move types
- Forgetting that pattern matching can move values
Controlling physical memory layouts and bypassing the global heap allocator is critical for latency-sensitive systems, embedded devices, and custom arenas. Rust enables deterministic memory management through the std::alloc::Allocator API and explicit layout control.
The Global Allocator Override
By default, Rust uses the system’s allocator (e.g., jemalloc on certain platforms or malloc via libc). You can override the global allocator using the #[global_allocator] attribute combined with a type implementing the GlobalAlloc trait.
rustuse std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
struct TrackingAllocator {
allocated: AtomicUsize,
}
#[global_allocator]
static GLOBAL: TrackingAllocator = TrackingAllocator {
allocated: AtomicUsize::new(0),
};
unsafe impl GlobalAlloc for TrackingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ret = System.alloc(layout);
if !ret.is_null() {
self.allocated.fetch_add(layout.size(), Ordering::SeqCst);
}
ret
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
System.dealloc(ptr, layout);
self.allocated.fetch_sub(layout.size(), Ordering::SeqCst);
}
}
fn main() {
let _data = vec![0u8; 1024 * 1024];
println!("Bytes allocated: {}", GLOBAL.allocated.load(Ordering::SeqCst));
}
Layout-Sensitive Data Structures
In high-performance systems, data alignment directly affects cache line utilization and vectorization (SIMD). The Layout primitive defines the size and alignment requirements for heap allocations.
rustuse std::alloc::{alloc, dealloc, Layout};
use std::ptr::NonNull;
struct AlignedBuffer {
ptr: NonNull<u8>,
layout: Layout,
}
impl AlignedBuffer {
pub fn new(size: usize, align: usize) -> Self {
let layout = Layout::from_size_align(size, align).expect("Invalid layout");
let ptr = unsafe {
let raw = alloc(layout);
NonNull::new(raw).unwrap_or_else(|| std::alloc::handle_alloc_error(layout))
};
Self { ptr, layout }
}
}
impl Drop for AlignedBuffer {
fn drop(&mut self) {
unsafe {
dealloc(self.ptr.as_ptr(), self.layout);
}
}
}
fn main() {
// Allocate 64 bytes aligned to 64-byte boundaries (cache line size)
let buf = AlignedBuffer::new(64, 64);
println!("Allocated at memory address: {:p}", buf.ptr.as_ptr());
}
Expected Output
textBytes allocated: 1048576
Allocated at memory address: 0x7f8a1c008000
Performance Considerations and Gotchas
- Alignment Overhead: Requesting strict alignments (e.g., 64 bytes) can cause internal fragmentation if structures are small.
- Allocator Locking: Global allocators often use internal mutexes or thread-local caches. Arena allocators bypass this by allocating large chunks upfront and bump-pointer allocating within them without thread contention.
- Unsafe Contracts: Implementing
GlobalAllocor manual pointer manipulation requires upholding strict safety invariants regarding alignment, non-null returns, and matching deallocation layouts.
Key Takeaways
- Override the global allocator using
#[global_allocator]andGlobalAllocto intercept and monitor all heap activity. - Use
std::alloc::Layoutto enforce precise byte alignments for SIMD operations and cache line optimizations. - Manual memory management via
allocanddeallocrequires explicit cleanup in aDropimplementation to prevent memory leaks.
Conditional Statements: if, else if, else
Conditional statements allow your program to make decisions and execute different code blocks based on conditions. Rust's if expressions are more powerful than in many languages.
Basic if Statement
rustfn main() {
let number = 7;
// Simple if statement
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
// if as an expression
let condition = true;
let result = if condition { 5 } else { 6 };
println!("The value of result is: {}", result);
// Each arm must return the same type
// This would error:
// let invalid = if condition { 5 } else { "six" };
}
if-else if-else Chain
rustlet score = 85;
if score >= 90 {
println!("Grade: A");
} else if score >= 80 {
println!("Grade: B");
} else if score >= 70 {
println!("Grade: C");
} else if score >= 60 {
println!("Grade: D");
} else {
println!("Grade: F");
}
// Using if expressions for assignment
let grade = if score >= 90 {
'A'
} else if score >= 80 {
'B'
} else if score >= 70 {
'C'
} else if score >= 60 {
'D'
} else {
'F'
};
println!("Your grade is: {}", grade);
Pattern Matching with if let
rust// if let for concise pattern matching
let some_value: Option<i32> = Some(42);
// Traditional match
match some_value {
Some(42) => println!("The answer to everything!"),
Some(x) => println!("Got some other value: {}", x),
None => println!("Got nothing"),
}
// Equivalent with if let
if let Some(42) = some_value {
println!("The answer to everything!");
} else if let Some(x) = some_value {
println!("Got some other value: {}", x);
} else {
println!("Got nothing");
}
// Combining conditions with patterns
let config_max = Some(3u8);
if let Some(max) = config_max && max > 5 {
println!("The maximum is configured to be {}", max);
} else {
println!("Maximum not configured or too small");
}
Complex Conditions
rust// Multiple conditions
let age = 25;
let has_license = true;
if age >= 18 && has_license {
println!("You can drive");
} else if age >= 18 && !has_license {
println!("You need to get a license first");
} else {
println!("You are too young to drive");
}
// Nested if statements
let number = 15;
if number % 2 == 0 {
println!("Number is even");
if number % 4 == 0 {
println!("Number is divisible by 4");
} else {
println!("Number is not divisible by 4");
}
} else {
println!("Number is odd");
if number % 3 == 0 {
println!("Number is divisible by 3");
}
}
// Using boolean expressions directly
let is_even = number % 2 == 0;
if is_even {
println!("The number is even");
}
Conditional with let-else
rust// let-else for pattern matching that must succeed
fn process_user_input(input: &str) {
let Ok(number) = input.parse::<i32>() else {
println!("Please input a valid number!");
return;
};
println!("You entered: {}", number);
}
// This is equivalent to:
fn process_user_input_alt(input: &str) {
let number = match input.parse::<i32>() {
Ok(n) => n,
Err(_) => {
println!("Please input a valid number!");
return;
}
};
println!("You entered: {}", number);
}
Common Pitfalls
- Forgetting that
ifconditions must be bool (no truthy/falsy values) - Mismatched types in if expression arms
- Using assignment
=instead of comparison==in conditions - Overusing nested if statements when match would be clearer
- Forgetting that patterns in if let can move values
for Loop in Rust
The for loop is the most common loop in Rust, used to iterate over collections, ranges, and any type that implements the Iterator trait.
Basic for Loop
rustfn main() {
// Iterate over a range
for number in 1..=5 {
println!("Count: {}", number);
}
// Iterate over array or vector
let numbers = [10, 20, 30, 40, 50];
for number in numbers {
println!("Number: {}", number);
}
// Iterate with reference (doesn't consume collection)
let names = vec!["Alice", "Bob", "Charlie"];
for name in &names {
println!("Name: {}", name);
}
// names is still usable here
// Iterate with mutable reference
let mut scores = vec![85, 92, 78];
for score in &mut scores {
*score += 5; // Add 5 to each score
}
println!("Updated scores: {:?}", scores);
}
Advanced for Loop Usage
rust// Using enumerate to get index
let fruits = ["apple", "banana", "cherry"];
for (index, fruit) in fruits.iter().enumerate() {
println!("Fruit {}: {}", index, fruit);
}
// Iterating over characters in a string
let text = "Hello";
for c in text.chars() {
println!("Character: {}", c);
}
// Iterating over bytes in a string
for byte in text.bytes() {
println!("Byte: {}", byte);
}
// Using ranges with steps
for i in (0..10).step_by(2) {
println!("Even: {}", i); // 0, 2, 4, 6, 8
}
// Reverse iteration
for i in (0..5).rev() {
println!("Countdown: {}", i); // 4, 3, 2, 1, 0
}
// Iterating over HashMap
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("red", 1);
map.insert("green", 2);
map.insert("blue", 3);
for (key, value) in &map {
println!("{}: {}", key, value);
}
Nested for Loops
rust// Multiplication table
for i in 1..=5 {
for j in 1..=5 {
print!("{}\t", i * j);
}
println!();
}
// Pattern printing
for i in 1..=5 {
for _ in 1..=i {
print!("*");
}
println!();
}
// Iterating over 2D array
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
for row in matrix.iter() {
for element in row.iter() {
print!("{} ", element);
}
println!();
}
Custom Iterators with for
rust// Any type that implements IntoIterator can be used in for loops
struct Counter {
count: u32,
max: u32,
}
impl Counter {
fn new(max: u32) -> Counter {
Counter { count: 0, max }
}
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.count < self.max {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
// Now we can use Counter in for loops
for number in Counter::new(5) {
println!("Counter: {}", number); // 1, 2, 3, 4, 5
}
// Using iterator adapters
let result: Vec<i32> = (1..=10)
.filter(|x| x % 2 == 0)
.map(|x| x * x)
.collect();
for value in result {
println!("Processed: {}", value); // 4, 16, 36, 64, 100
}
Common Pitfalls
- Using
forwith types that don't implement Iterator - Accidentally consuming collections with
into_iter() - Modifying a collection while iterating over it
- Forgetting that range upper bound is exclusive:
1..5gives 1,2,3,4 - Using wrong iterator method (
iter()vsinto_iter()vsiter_mut())
Structuring large-scale Rust codebases requires virtual workspaces for shared dependency management and optimized profiles that balance compilation speed with production binary performance. Mastering multi-crate separation and profile tuning prevents bloated binaries and long CI/CD build times.
Structuring a Multi-Crate Workspace
As applications scale, monolithic codebases degrade in compile times and architectural clarity. Cargo workspaces allow multiple sub-crates to share a single Cargo.lock file and a common target directory, preventing redundant compilation of shared dependencies.
Consider a project layout separating domain logic, persistence, and the application boundary:
textmy_workspace/
├── Cargo.toml
├── core_domain/
│ ├── Cargo.toml
│ └── src/lib.rs
├── persistence/
│ ├── Cargo.toml
│ └── src/lib.rs
└── server/
├── Cargo.toml
└── src/main.rs
The root Cargo.toml acts as the workspace coordinator. Use workspace inheritance ([workspace.package] and [workspace.dependencies]) to enforce uniform compiler lints, editions, and dependency versions across all crates.
toml# Root Cargo.toml
[workspace]
members = [
"core_domain",
"persistence",
"server"
]
resolver = "2"
[workspace.package]
version = "0.1.0"
edition = "2021"
authors = ["Old Lane 17 Engineering"]
rust-version = "1.75"
[workspace.dependencies]
tokio = { version = "1.36", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
sqlx = { version = "0.7", features = ["runtime-tokio", "tls-rustls", "postgres"] }
core_domain = { path = "core_domain" }
persistence = { path = "persistence" }
In individual sub-crates (e.g., server/Cargo.toml), inherit these configurations to keep manifests dry and maintain consistency:
toml[package]
name = "server"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[dependencies]
tokio.workspace = true
serde.workspace = true
core_domain.workspace = true
persistence.workspace = true
Optimizing Build Profiles for Production
Default Cargo release profiles prioritize compilation time and standard optimizations over maximum binary reduction and CPU-specific execution speed. To squeeze maximum performance and minimal binary footprint for production deployment, tune the [profile.release] tier in the root Cargo.toml.
toml[profile.release]
opt-level = 3 # Maximum optimizations for speed
lto = "fat" # Link-Time Optimization across all crates
codegen-units = 1 # Single codegen unit allows LLVM maximum optimization reach
panic = "abort" # Remove unwinding infrastructure, shrinking binary size
strip = "debuginfo" # Strip symbols from binary to drastically reduce size
Performance and Edge Case Trade-offs
codegen-units = 1: Dramatically improves runtime performance and enables aggressive inlining, but severely increases single-threaded compilation times. Use higher values (e.g.,16) in development profiles, but enforce1in CI/CD release pipelines.panic = "abort": Eliminates stack-unwinding code generation. While it reduces binary size and speeds up panic cleanup, any third-party code relying on catching panics (std::panic::catch_unwind) will fail catastrophically. Verify library dependencies before enabling.lto = "fat": Cross-crate optimization exposes deep inlining opportunities. If link times become a bottleneck in CI, considerlto = "thin".
Try It Yourself
Initialize a local workspace, wire up a shared internal dependency, and build it with optimized production profiles.
bash# 1. Initialize workspace structure
cargo new --lib core_domain
cargo new --lib persistence
cargo new --bin server
# 2. Configure root Cargo.toml using the examples above, then build:
cargo build --release --workspace
Expected Output
text Compiling core_domain v0.1.0 (/path/to/my_workspace/core_domain)
Compiling persistence v0.1.0 (/path/to/my_workspace/persistence)
Compiling server v0.1.0 (/path/to/my_workspace/server)
Finished release [optimized] target(s) in 4.12s
Key Takeaways
- Use Cargo workspaces with
resolver = "2"to share dependencies and lockfiles efficiently across domain boundaries. - Leverage workspace inheritance (
.workspace = true) to centralize dependency versions, editions, and compiler lints. - Set
opt-level = 3,lto = "fat",codegen-units = 1, andpanic = "abort"in production release profiles to optimize for execution speed and minimal binary footprint. - Balance compile-time costs: aggressive optimization profiles (
codegen-units = 1,lto = "fat") should be reserved for release and CI environments, keeping development cycles fast.
Const generics and compile-time evaluation eliminate runtime overhead and prevent dimensional mismatches in scientific and engineering software by shifting validation into the type system.
Type-Safe Dimensional Vectors
Traditional array wrappers rely on dynamic lengths, introducing runtime bounds checking and allocation costs. By lifting array sizes and physical units into the type system via const generics and trait bounds, Rust guarantees safety at zero runtime cost.
rustuse std::ops::{Add, Sub};
use std::marker::PhantomData;
// Marker traits and types for dimensional analysis
pub trait Dimension: Send + Sync + 'static {}
#[derive(Debug, Clone, Copy)]
pub struct Length;
impl Dimension for Length {}
#[derive(Debug, Clone, Copy)]
pub struct Mass;
impl Dimension for Mass {}
// A statically sized, dimension-aware vector
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vector<T, const N: usize, D: Dimension> {
data: [T; N],
_dim: PhantomData<D>,
}
impl<T, const N: usize, D: Dimension> Vector<T, N, D> {
pub const fn new(data: [T; N]) -> Self {
Self { data, _dim: PhantomData }
}
}
// Addition is only valid if dimensions and lengths match perfectly
impl<T: Add<Output = T> + Copy, const N: usize, D: Dimension> Add for Vector<T, N, D> {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
let mut result = self.data;
let mut i = 0;
while i < N {
result[i] = self.data[i] + rhs.data[i];
i += 1;
}
Self::new(result)
}
}
fn main() {
let pos1 = Vector::<f64, 3, Length>::new([1.0, 2.0, 3.0]);
let pos2 = Vector::<f64, 3, Length>::new([4.0, 5.0, 6.0]);
// Compiles successfully: matching dimensions and lengths
let sum = pos1 + pos2;
println!("Position sum: {:?}", sum);
// COMPILE ERROR IF UNCOMMENTED:
// Mismatched dimensions (Length vs Mass)
// let mass = Vector::<f64, 3, Mass>::new([1.0, 1.0, 1.0]);
// let _fail = pos1 + mass;
// COMPILE ERROR IF UNCOMMENTED:
// Mismatched sizes (3 vs 2)
// let pos_2d = Vector::<f64, 2, Length>::new([1.0, 2.0]);
// let _fail2 = pos1 + pos_2d;
}
Advanced Const Expressions and Evaluation
Advanced const generics often require operations on generic parameters. While full generic const expressions (e.g., [T; N + 1]) are still stabilizing behind feature gates, we can use trait-based associated consts to compute derived layouts at compile time.
rustpub trait MatrixLayout {
const ROWS: usize;
const COLS: usize;
const CAPACITY: usize = Self::ROWS * Self::COLS;
}
pub struct Matrix<T, L: MatrixLayout> {
data: [T; L::CAPACITY],
_layout: PhantomData<L>,
}
pub struct SquareMatrix<const N: usize>;
impl<const N: usize> MatrixLayout for SquareMatrix<N> {
const ROWS: usize = N;
const COLS: usize = N;
}
impl<T: Default + Copy, const N: usize> Matrix<T, SquareMatrix<N>> {
pub fn identity() -> Self {
let mut data = [T::default(); SquareMatrix::<N>::CAPACITY];
let mut i = 0;
while i < N {
// Index calculation: row * N + col
// For identity, we want data[i * N + i] = 1 (or equivalent)
i += 1;
}
Self { data, _layout: PhantomData }
}
}
Expected Output
textPosition sum: Vector { data: [5.0, 7.0, 9.0], _dim: PhantomData }
Performance Considerations and Gotchas
- Monomorphization Bloat: Every unique combination of const generic parameters (
N) generates a distinct set of machine code instructions. Avoid excessive granularity if code size is constrained. - Const Evaluation Limits: Complex loops inside
const fnare restricted in stable Rust unless using nightly features (generic_const_exprs). Keep compile-time logic deterministic and straightforward. - Zero-Sized Markers: Use
PhantomData<D>to bind type-level units without adding runtime memory footprint to the struct layout.
Key Takeaways
- Const generics lift configuration parameters (like array bounds) directly into the type system, catching boundary bugs at compile time.
- Combining const parameters with marker traits (
Dimension) implements zero-cost domain logic enforcement. - Operations on const generics execute completely at compile time, leaving zero runtime overhead in the generated assembly.
while Loop in Rust
The while loop repeats a block of code as long as a condition is true. It's useful when you don't know in advance how many iterations are needed.
Basic while Loop
rustfn main() {
// Count from 1 to 5
let mut i = 1;
while i <= 5 {
println!("Count: {}", i);
i += 1;
}
// User input validation
let mut input = String::new();
println!("Enter a positive number: ");
// This is simplified - real input handling would be more complex
while input.trim().parse::<i32>().unwrap_or(0) <= 0 {
input.clear();
println!("Invalid input. Enter a positive number: ");
// In real code, you would read from stdin here
input = "42".to_string(); // Simulating valid input
}
println!("Thank you! You entered: {}", input);
}
while let Pattern
rust// while let for pattern matching that might fail
let mut stack = Vec::new();
stack.push(1);
stack.push(2);
stack.push(3);
// Pop elements until empty
while let Some(top) = stack.pop() {
println!("Popped: {}", top);
}
// Processing streams of data
let mut data = vec![Some(1), Some(2), None, Some(4)];
let mut iter = data.iter_mut();
while let Some(Some(value)) = iter.next() {
*value *= 2;
}
println!("Processed: {:?}", data); // [Some(2), Some(4), None, Some(8)]
// Reading until sentinel value (conceptual)
let mut values = vec![1, 2, 3, 0, 4, 5];
let mut sum = 0;
let mut index = 0;
while index < values.len() && values[index] != 0 {
sum += values[index];
index += 1;
}
println!("Sum until zero: {}", sum); // 6
Practical while Loop Examples
rust// Game loop example
fn game_loop() {
let mut game_over = false;
let mut score = 0;
while !game_over {
// Simulate game round
score += 10;
println!("Score: {}", score);
// Check win condition
if score >= 100 {
game_over = true;
println!("You win!");
}
// In real game, this would have some condition
if score > 50 {
// Simulating random game over
game_over = true;
println!("Game over!");
}
}
}
// Processing until condition
fn find_first_negative(numbers: &[i32]) -> Option<usize> {
let mut index = 0;
while index < numbers.len() {
if numbers[index] < 0 {
return Some(index);
}
index += 1;
}
None
}
let data = [1, 2, -3, 4, 5];
if let Some(pos) = find_first_negative(&data) {
println!("First negative at position: {}", pos);
}
// Infinite loop with break (often better than while true)
let mut counter = 0;
loop {
counter += 1;
if counter > 5 {
break;
}
println!("Counter: {}", counter);
}
Loop Control in while
rustlet mut x = 0;
// Using continue
while x < 10 {
x += 1;
if x % 2 == 0 {
continue; // Skip even numbers
}
println!("Odd: {}", x); // 1, 3, 5, 7, 9
}
// Using break with value
let mut attempt = 0;
let result = loop {
attempt += 1;
if attempt > 3 {
break "failed";
}
// Simulate some operation that might succeed
if attempt == 2 {
break "success";
}
};
println!("Result: {}", result); // success
// Nested loops with labels
let mut i = 0;
'outer: while i < 3 {
let mut j = 0;
while j < 3 {
if i * j > 4 {
println!("Breaking both loops at i={}, j={}", i, j);
break 'outer;
}
println!("i={}, j={}", i, j);
j += 1;
}
i += 1;
}
Common Pitfalls
- Infinite loops when condition never becomes false
- Forgetting to update the loop control variable
- Using
while trueinstead ofloopfor infinite loops - Modifying data being iterated over (can cause bugs or panics)
- Off-by-one errors in loop conditions
Loop Control Statements
Rust provides loop control statements to alter the normal flow of loops: break, continue, and loop labels. These work with all loop types (loop, while, for).
break and continue
rustfn main() {
// break exits the loop immediately
for i in 1..=10 {
if i == 5 {
break; // Exit loop when i reaches 5
}
println!("{}", i);
}
// Output: 1 2 3 4
// continue skips the rest of current iteration
for i in 1..=10 {
if i % 2 == 0 {
continue; // Skip even numbers
}
println!("{}", i); // Only odd numbers printed
}
// Output: 1 3 5 7 9
// break with value (only in loop, not while or for)
let result = loop {
let number = 7;
if number > 5 {
break number * 2; // Break with value
}
};
println!("The result is {}", result); // 14
}
Loop Labels
rust// Labeling loops for control
'outer: for i in 1..=3 {
'inner: for j in 1..=3 {
if i * j > 4 {
println!("Breaking outer loop at i={}, j={}", i, j);
break 'outer; // Break both loops
}
println!("i={}, j={}", i, j);
}
}
/* Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
Breaking outer loop at i=2, j=3
*/
// Continue with labels
'outer: for i in 1..=3 {
for j in 1..=3 {
if i == 2 && j == 2 {
println!("Skipping i=2, j=2");
continue 'outer; // Continue outer loop
}
println!("i={}, j={}", i, j);
}
}
/* Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
Skipping i=2, j=2
i=3, j=1
i=3, j=2
i=3, j=3
*/
Practical Loop Control Examples
rust// Search example with break
fn find_number(numbers: &[i32], target: i32) -> Option<usize> {
for (index, &number) in numbers.iter().enumerate() {
if number == target {
return Some(index); // Early return works like break
}
}
None
}
let data = [10, 20, 30, 40, 50];
if let Some(pos) = find_number(&data, 30) {
println!("Found at position: {}", pos);
}
// Input validation with continue
let mut valid_inputs = 0;
for attempt in 1..=5 {
// Simulate input - some are invalid
let input = if attempt % 2 == 0 { "42" } else { "invalid" };
if input.parse::<i32>().is_err() {
println!("Attempt {}: Invalid input, skipping...", attempt);
continue;
}
valid_inputs += 1;
println!("Attempt {}: Valid input received", attempt);
}
println!("Total valid inputs: {}", valid_inputs);
// Complex condition with break and continue
let mut count = 0;
for i in 1..=100 {
if i % 3 == 0 && i % 5 == 0 {
println!("FizzBuzz");
continue;
}
if i % 3 == 0 {
println!("Fizz");
continue;
}
if i % 5 == 0 {
println!("Buzz");
continue;
}
count += 1;
if count > 10 {
println!("Reached limit of 10 numbers");
break;
}
println!("{}", i);
}
Loop Control in Different Contexts
rust// In while loops
let mut x = 0;
while x < 10 {
x += 1;
if x == 5 {
continue; // Skip the rest when x is 5
}
if x == 8 {
break; // Exit when x is 8
}
println!("x = {}", x);
}
// Output: 1 2 3 4 6 7
// In nested loops without labels
for i in 1..=3 {
for j in 1..=3 {
if i * j > 4 {
println!("Breaking inner loop at i={}, j={}", i, j);
break; // Only breaks inner loop
}
println!("i={}, j={}", i, j);
}
}
/* Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
Breaking inner loop at i=2, j=3
i=3, j=1
Breaking inner loop at i=3, j=2
*/
// Using return instead of break for function exit
fn process_data(data: &[i32]) -> Option<i32> {
for &value in data {
if value < 0 {
println!("Negative value found, aborting");
return None; // Exit entire function
}
if value == 0 {
println!("Zero found, skipping");
continue; // Continue to next iteration
}
println!("Processing: {}", value);
}
Some(42) // Success case
}
Common Pitfalls
- Using
breakwhencontinueis more appropriate - Forgetting that
breakwith value only works inloop - Overusing loop labels can make code harder to read
breakwithout labels only exits the innermost loop- Placing code after
continuethat will never execute
Encode domain rules directly into the Rust type system so illegal states become unrepresentable at compile time, completely eliminating runtime overhead.
The Newtype Pattern: Eliminating Primitive Obsession
Passing raw primitives like String or u64 across domain boundaries introduces catastrophic logic bugs (e.g., confusing user IDs with order IDs, or unvalidated input with sanitized input). The newtype pattern wraps a primitive type in a distinct, zero-cost tuple struct.
rustuse std::fmt;
// Define a distinct type for validated user emails
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Email(String);
impl Email {
pub fn parse(input: impl Into<String>) -> Result<Self, &'static str> {
let s = input.into();
if s.contains('@') && s.len() > 3 {
Ok(Self(s))
} else {
Err("Invalid email format")
}
}
pub fn as_str(&self) -> &str {
&self.as_ref()
}
}
impl AsRef<str> for Email {
fn as_ref(&self) -> &str {
&self.drain_to_str() // conceptually returning inner str
&self.0
}
}
fn send_welcome_email(email: &Email) {
println!("Sending onboarding payload to: {}", email.as_ref());
}
fn main() {
let raw = "admin@oldlane17.com";
match Email::parse(raw) {
Ok(valid_email) => send_welcome_email(&valid_email),
Err(e) => eprintln!("Error: {}", e),
}
// COMPILE ERROR: Mismatched types!
// let fake_id: String = "1234".to_string();
// send_welcome_email(&fake_id);
}
The Rust compiler erases newtype wrappers entirely during optimization. Email has the exact same memory footprint and CPU register layout as a raw String.
The Type-State Pattern: Compile-Time State Machines
The type-state pattern uses marker types to encode an object’s lifecycle in its generic parameters. This prevents calling methods in the wrong order (e.g., fulfilling an order before it has been paid for).
rustuse std::marker::PhantomData;
// States
pub struct Draft;
pub struct Paid;
pub struct Fulfilled;
// Order struct parameterized by State
pub struct Order<State> {
id: u64,
amount_cents: u32,
_state: PhantomData<State>,
}
impl Order<Draft> {
pub fn new(id: u64, amount_cents: u32) -> Self {
Self {
id,
amount_cents,
_state: PhantomData,
}
}
pub fn pay(self) -> Order<Paid> {
// Process payment gateway logic here...
println!("Order {} paid successfully.", self.id);
Order {
id: self.id,
amount_cents: self.amount_cents,
_state: PhantomData,
}
}
}
impl Order<Paid> {
pub fn fulfill(self) -> Order<Fulfilled> {
println!("Order {} shipped to customer.", self.id);
Order {
id: self.id,
amount_cents: self.amount_cents,
_state: PhantomData,
}
}
}
fn main() {
let order = Order::new(42, 1500);
// Valid lifecycle transition
let paid_order = order.pay();
let _fulfilled_order = paid_order.fulfill();
// COMPILE ERROR: Cannot fulfill an order that is still in Draft state!
// let premature = Order::new(43, 2000);
// premature.fulfill();
}
Performance and Edge Cases
- Zero Runtime Cost: `PhantomData
` takes 0 bytes of memory. The state transitions exist strictly within the compiler's semantic analysis phase. - Consuming Self (`self`): By taking ownership of `self` on state-transition methods, Rust prevents reuse of the old state via affine type systems.
- Ergonomics vs Safety: Deep pipelines can lead to verbose type signatures. Use type aliases or associated types if signatures grow too complex.
Key Takeaways
- Newtypes eradicate primitive obsession by converting values into domain-specific types with zero runtime penalty.
- The compiler optimizes newtype wrappers down to the exact performance profile of their inner primitive types.
- The type-state pattern uses `PhantomData` and ownership semantics to make invalid state transitions compile errors.
- Consuming `self` during state transitions guarantees that outdated object references cannot be reused.
Rust’s async model relies on heap-or-stack structural guarantees where futures containing self-referential borrows cannot be safely moved in memory. This chapter covers the low-level mechanics of Pin, the Unpin marker trait, and how executors poll futures to completion.
Self-Referential Structs and Memory Pinning
In standard Rust, moving a value via assignment (let b = a;) copies its bytes to a new memory address. If a struct contains a pointer to one of its own fields, a standard memory move invalidates that internal pointer, leading to undefined behavior.
rustuse std::pin::Pin;
use std::marker::PhantomPinned;
// A self-referential struct: `slice` points to `data`.
struct SelfRef {
data: String,
slice: *const str,
_marker: PhantomPinned, // Opts out of `Unpin`
}
impl SelfRef {
fn new(data: String) -> Self {
let mut res = SelfRef {
data,
slice: std::ptr::null(),
_marker: PhantomPinned,
};
// Safety: We establish the self-referential pointer after allocation.
let slice_ptr = &res.data as &str as *const str;
res.slice = slice_ptr;
res
}
fn slice<'a>(self: Pin<&Self>, _cx: &mut std::task::Context<'_>) -> &'a str {
// Safety: Because we are pinned, we guarantee the memory won't move.
unsafe { &*self.slice }
}
}
The PhantomPinned marker is a zero-sized type that explicitly removes the automatic Unpin implementation from your struct. Without it, any consumer could call std::mem::swap or move the value freely.
Pin and Unpin Mechanics
Pin<P> is a wrapper around a pointer type P (like Box<T>, &mut T, or Rc<T>) that guarantees the pointee T will never be moved again unless T implements Unpin.
Unpin: A marker trait implemented automatically for almost all standard types (integers, strings, standard structs). It signals that it is safe to move the type even when wrapped in aPin.!Unpin: Types containingPhantomPinnedor async/await blocks (which hold local borrows across.awaityield points) are!Unpin.
rustuse std::pin::Pin;
fn assert_unpin<T: Unpin>() {}
fn main() {
// Standard types are Unpin; Pin<&mut T> for Unpin acts just like &mut T.
assert_unpin::<i32>();
assert_unpin::<String>();
let mut val = 42;
let pinned: Pin<&mut i32> = Pin::new(&mut val);
// Because i32 is Unpin, we can extract the mutable reference back out:
let unpinned_ref: &mut i32 = pinned.get_mut();
*unpinned_ref = 100;
}
When dealing with !Unpin types, you cannot call .get_mut() safely. Instead, you must use projections (map_unchecked_mut) while maintaining structural pinning invariants.
Async Runtime Internals: Driving Futures
An async fn compiles into an anonymous state machine enum implementing the Future trait. The Future::poll method drives execution:
rustpub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output>;
}
Because self is passed as Pin<&mut Self>, the runtime guarantees that the future state machine will remain at a stable memory address throughout its entire lifecycle.
Below is a primitive, single-threaded executor implementation demonstrating how runtimes poll futures and handle task waking via Waker.
rustuse std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
// A basic timer future that completes after a duration.
struct TimerFuture {
shared_state: Arc<SharedState>,
}
struct SharedState {
completed: AtomicBool,
waker: std::sync::Mutex<Option<Waker>>,
}
impl Future for TimerFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.shared_state.completed.load(Ordering::Acquire) {
Poll::Ready(())
} else {
// Register the current waker so the background thread can wake us up.
let mut waker = self.shared_state.waker.lock().unwrap();
*waker = Some(cx.waker().clone());
Poll::Pending
}
}
}
impl TimerFuture {
fn new(dur: Duration) -> Self {
let shared_state = Arc::new(SharedState {
completed: AtomicBool::new(false),
waker: std::sync::Mutex::new(None),
});
let thread_state = Arc::clone(&shared_state);
thread::spawn(move || {
thread::sleep(dur);
thread_state.completed.store(true, Ordering::Release);
if let Some(waker) = thread_state.waker.lock().unwrap().take() {
waker.wake();
}
});
TimerFuture { shared_state }
}
}
// Minimal Executor Implementation
fn block_on<F: Future>(mut future: F) -> F::Output {
use std::task::RawWaker, std::task::RawWakerVTable;
// Create a dummy waker for single-threaded execution context
fn clone(_: *const ()) -> RawWaker { raw_waker() }
fn wake(_: *const ()) {}
fn wake_by_ref(_: *const ()) {}
fn drop(_: *const ()) {}
const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop);
fn raw_waker() -> RawWaker {
RawWaker::new(std::ptr::null(), &VTABLE)
}
let waker = unsafe { Waker::from_raw(raw_waker()) };
let mut cx = Context::from_waker(&waker);
// Pin the future to the stack
let mut pinned = unsafe { Pin::new_unchecked(&mut future) };
loop {
match pinned.as_mut().poll(&mut cx) {
Poll::Ready(output) => return output,
Poll::Pending => {
// In a real runtime, the thread would park here until woken.
thread::park_timeout(Duration::from_millis(10));
}
}
}
}
fn main() {
println!("Starting timer future...");
block_on(async {
TimerFuture::new(Duration::from_millis(100)).await;
println!("Timer completed!");
});
}
Expected Output
```text Starting timer future... Timer completed! ```Gotchas and Performance Considerations
- Stack vs. Heap Pinning: Use
Box::pin(future)to move an!Unpinfuture onto the heap when passing it across thread boundaries or dynamic dispatch boundaries. Usepin! macro(std::pin::pin!) for zero-cost stack pinning in modern Rust (1.68+). - Accidental Unpin Opt-in: Adding a field that is not
Unpin(or forgettingPhantomPinned) can subtly break pin guarantees if refactored carelessly. Always verify your bounds when writing custom futures. - Waker Over-Notification: Spurious wakes must be handled gracefully by futures. A call to
wake()simply indicates that progress might be possible, requiringpollto re-verify state.
Key Takeaways
Pin<P>prevents values from moving in memory, ensuring safety for self-referential structs and async state machines.- The
Unpinmarker trait dictates whether a type can be safely moved out of aPinwrapper. - Async runtimes drive futures by repeatedly calling
Future::pollwith a validContextand a stack- or heap-pinned future reference. - Custom futures use
Wakerto notify the runtime executor when an asynchronous resource becomes available.
Nested Loops in Rust
Nested loops are loops within loops. They are essential for working with multi-dimensional data, matrices, and complex patterns.
Basic Nested Loops
rustfn main() {
// Simple nested loop
for i in 1..=3 {
for j in 1..=3 {
println!("({}, {})", i, j);
}
}
/* Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3) */
// Multiplication table
println!("\nMultiplication Table:");
for i in 1..=5 {
for j in 1..=5 {
print!("{}\t", i * j);
}
println!();
}
}
Pattern Printing with Nested Loops
rustlet rows = 5;
// Right triangle
for i in 1..=rows {
for _ in 1..=i {
print!("*");
}
println!();
}
/* Output:
*
**
***
****
*****
*/
// Inverted triangle
for i in (1..=rows).rev() {
for _ in 1..=i {
print!("*");
}
println!();
}
/* Output:
*****
****
***
**
*
*/
// Pyramid
for i in 1..=rows {
// Print spaces
for _ in 1..=(rows - i) {
print!(" ");
}
// Print stars
for _ in 1..=(2 * i - 1) {
print!("*");
}
println!();
}
/* Output:
*
***
*****
*******
*********
*/
Working with 2D Arrays
rust// Matrix operations
const ROWS: usize = 3;
const COLS: usize = 3;
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Print matrix
println!("Matrix:");
for i in 0..ROWS {
for j in 0..COLS {
print!("{} ", matrix[i][j]);
}
println!();
}
// Sum of all elements
let mut sum = 0;
for i in 0..ROWS {
for j in 0..COLS {
sum += matrix[i][j];
}
}
println!("Sum of all elements: {}", sum);
// Transpose matrix
println!("Transpose:");
for j in 0..COLS {
for i in 0..ROWS {
print!("{} ", matrix[i][j]);
}
println!();
}
// Element-wise operations
let mut result = [[0; COLS]; ROWS];
for i in 0..ROWS {
for j in 0..COLS {
result[i][j] = matrix[i][j] * 2;
}
}
println!("Doubled matrix: {:?}", result);
Mixed Loop Types
rust// while inside for
for i in 1..=3 {
let mut j = 1;
while j <= 3 {
println!("i={}, j={}", i, j);
j += 1;
}
}
// loop inside for
for i in 1..=2 {
let mut j = 1;
loop {
println!("i={}, j={}", i, j);
j += 1;
if j > 2 {
break;
}
}
}
// Using different loop controls in nested loops
'outer: for i in 1..=3 {
for j in 1..=3 {
if i == 2 && j == 2 {
println!("Skipping i=2, j=2");
continue 'outer; // Continue to next i
}
if i * j > 6 {
println!("Product too large at i={}, j={}", i, j);
break 'outer; // Break both loops
}
println!("i={}, j={}, product={}", i, j, i * j);
}
}
Performance Considerations
rust// Cache-friendly iteration (row-major order)
let mut matrix = [[0; 1000]; 1000];
// Good: Iterate row by row (cache-friendly)
for i in 0..1000 {
for j in 0..1000 {
matrix[i][j] = i + j;
}
}
// Bad: Iterate column by column (cache-unfriendly)
// for j in 0..1000 {
// for i in 0..1000 {
// matrix[i][j] = i + j;
// }
// }
// Using iterators for nested loops (often more efficient)
let data = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
let flat: Vec<i32> = data.iter().flatten().cloned().collect();
println!("Flattened: {:?}", flat);
let sum: i32 = data.iter().flatten().sum();
println!("Total sum: {}", sum);
// Using enumerate for indices in nested loops
for (i, row) in data.iter().enumerate() {
for (j, &value) in row.iter().enumerate() {
println!("data[{}][{}] = {}", i, j, value);
}
}
Common Pitfalls
- O(n²) time complexity can be inefficient for large data
- Using wrong loop variables in inner vs outer loops
- Cache-unfriendly access patterns in multi-dimensional arrays
- Excessive nesting reduces readability (try to keep to 2-3 levels)
- Forgetting to break/continue the correct loop when using labels
Rust enables robust multi-platform libraries through declarative target-specific dependencies, feature flags, and attributes (cfg, cfg_attr) resolved at compile time.
Target-Specific Dependencies
Manage platform divergences without polluting core source files by declaring target-specific dependencies in Cargo.toml. Use the [target.'cfg(...)'.dependencies] syntax to scope libraries to specific operating systems, architectures, or environments.
toml[package]
name = "fs_util"
version = "0.1.0"
edition = "2021"
[dependencies]
# Dependencies compiled for all platforms
log = "0.4"
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["fileapi", "handleapi"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
Cargo evaluates these selectors against the target triple during compilation, pulling down and compiling OS-specific crates only when targeted.
Conditional Compilation Attributes
Use the #[cfg(...)] attribute to conditionally include modules, functions, or blocks of code based on target architecture, operating system, or custom features.
rust// src/lib.rs
// Conditionally compile entire modules based on OS
#[cfg(target_os = "windows")]
mod windows_impl;
#[cfg(target_os = "unix")]
mod unix_impl;
// Conditionally compile a single function implementation
pub fn get_temp_dir() -> std::path::PathBuf {
#[cfg(target_os = "windows")]
{
windows_impl::internal_get_temp()
}
#[cfg(target_os = "unix")]
{
unix_impl::internal_get_temp()
}
}
The cfg! macro evaluates boolean expressions at compile time, allowing runtime branch pruning when combined with if statements:
rustpub fn configure_socket() {
if cfg!(target_os = "linux") {
// This block is completely optimized away by LLVM on non-Linux targets
println!("Applying Linux-specific socket optimizations");
}
}
Custom Feature Flags
Expose optional functionality by declaring features in Cargo.toml and querying them with #[cfg(feature = "...")].
toml[features]
default = []
async-io = ["dep:tokio", "dep:bytes"]
[dependencies]
tokio = { version = "1.0", features = ["net"], optional = true }
bytes = { version = "1.0", optional = true }
Using the dep: prefix syntax (Cargo 1.60+) implicitly enables the dependency when the feature is active without needing to declare it in the [features] list as an explicit toggle.
rust#[cfg(feature = "async-io")]
pub async fn read_data(socket: &tokio::net::TcpStream) {
// Async implementation utilizing tokio
}
Try It Yourself
Test conditional compilation locally by cross-compiling or targeting specific platforms using cargo flags.
bash# Compile specifically for Windows from a Linux/macOS host (requires target installed via rustup)
cargo build --target x86_64-pc-windows-gnu
# Compile with a custom feature enabled
cargo build --features async-io
Gotchas and Edge Cases
- IDE Support: When using target-specific dependencies, your IDE (such as rust-analyzer) might flag missing imports if it is configured for your host platform rather than the compilation target. Configure your editor's target triple to match your deployment target.
- API Drift: Conditional compilation can lead to neglected code paths. Always run CI pipelines that compile across Windows, macOS, and Linux targets to prevent target-specific regressions.
Key Takeaways
- Isolate OS-specific dependencies inside `Cargo.toml` using `[target.'cfg(...)'.dependencies]` to keep builds lean.
- Use `#[cfg(target_os = "...")]` to branch logic or module structures at compile time.
- Leverage `cfg!` macro evaluations for clean, branch-pruned platform checks inside standard code blocks.
- Utilize Cargo features with the `dep:` prefix to make heavy dependencies strictly optional.
Functions in Rust
Functions are reusable blocks of code that perform specific tasks. Rust functions are first-class citizens and support features like pattern matching, multiple return values, and closures.
Function Definition and Usage
rust// Function declaration
fn greet() {
println!("Hello, world!");
}
// Function with parameters and return type
fn add_numbers(a: i32, b: i32) -> i32 {
a + b // No semicolon - this is an expression, not a statement
}
// Function with explicit return
fn subtract_numbers(a: i32, b: i32) -> i32 {
return a - b; // Explicit return with semicolon
}
// Function with multiple parameters
fn print_info(name: &str, age: u32) {
println!("{} is {} years old", name, age);
}
fn main() {
greet();
let sum = add_numbers(5, 3);
println!("5 + 3 = {}", sum);
let difference = subtract_numbers(10, 4);
println!("10 - 4 = {}", difference);
print_info("Alice", 30);
}
Function Parameters and Ownership
rust// Pass by value (takes ownership)
fn take_ownership(s: String) {
println!("I own: {}", s);
} // s is dropped here
// Pass by immutable reference (borrows)
fn borrow_immutable(s: &String) -> usize {
s.len()
} // s is not dropped - it's just a reference
// Pass by mutable reference (mutably borrows)
fn borrow_mutable(s: &mut String) {
s.push_str(" world");
}
fn main() {
let s1 = String::from("hello");
// take_ownership(s1); // s1 is moved, can't use it after
// println!("{}", s1); // This would error
let len = borrow_immutable(&s1); // s1 is still owned here
println!("Length: {}, s1: {}", len, s1);
let mut s2 = String::from("hello");
borrow_mutable(&mut s2);
println!("After mutation: {}", s2);
}
Returning Values from Functions
rust// Returning multiple values using tuples
fn calculate_stats(numbers: &[i32]) -> (i32, i32, f64) {
let sum: i32 = numbers.iter().sum();
let count = numbers.len() as i32;
let average = sum as f64 / count as f64;
(sum, count, average) // Return tuple
}
// Returning Option for functions that might fail
fn divide(a: f64, b: f64) -> Option<f64> {
if b == 0.0 {
None
} else {
Some(a / b)
}
}
// Returning Result for error handling
fn parse_number(s: &str) -> Result<i32, std::num::ParseIntError> {
s.parse()
}
// Early return with condition
fn find_first_even(numbers: &[i32]) -> Option<usize> {
for (i, &num) in numbers.iter().enumerate() {
if num % 2 == 0 {
return Some(i); // Early return
}
}
None // Return None if no even numbers found
}
fn main() {
let data = [1, 2, 3, 4, 5];
let (sum, count, avg) = calculate_stats(&data);
println!("Sum: {}, Count: {}, Average: {:.2}", sum, count, avg);
match divide(10.0, 2.0) {
Some(result) => println!("Division result: {}", result),
None => println!("Cannot divide by zero"),
}
match parse_number("42") {
Ok(num) => println!("Parsed number: {}", num),
Err(e) => println!("Parse error: {}", e),
}
}
Advanced Function Features
rust// Generic functions
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = item;
}
}
largest
}
// Function pointers
fn add_one(x: i32) -> i32 {
x + 1
}
fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
f(f(arg))
}
// Closures (anonymous functions)
let closure = |x: i32| -> i32 { x * 2 };
let closure_inferred = |x| x * 2; // Type inference
// Higher-order functions
fn apply_to_numbers(numbers: &[i32], f: fn(i32) -> i32) -> Vec<i32> {
numbers.iter().map(|&x| f(x)).collect()
}
fn main() {
let numbers = [1, 2, 3, 4, 5];
let biggest = largest(&numbers);
println!("Largest number: {}", biggest);
let result = do_twice(add_one, 5);
println!("Result: {}", result); // 7
let doubled = apply_to_numbers(&numbers, |x| x * 2);
println!("Doubled: {:?}", doubled); // [2, 4, 6, 8, 10]
}
Method Syntax and Associated Functions
ruststruct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// Associated function (like static method)
fn square(size: u32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}
// Method - takes &self
fn area(&self) -> u32 {
self.width * self.height
}
// Method - takes &mut self
fn scale(&mut self, factor: u32) {
self.width *= factor;
self.height *= factor;
}
// Method - takes self (consumes)
fn into_tuple(self) -> (u32, u32) {
(self.width, self.height)
}
}
fn main() {
let square = Rectangle::square(10);
println!("Square area: {}", square.area());
let mut rect = Rectangle { width: 30, height: 50 };
println!("Area: {}", rect.area());
rect.scale(2);
println!("Scaled area: {}", rect.area());
let (w, h) = rect.into_tuple();
println!("Dimensions: {}x{}", w, h);
}
Common Pitfalls
- Forgetting semicolon in functions that return
() - Mixing up when to use
&,&mut, or take ownership - Returning references to local variables
- Not handling all cases in functions returning Option/Result
- Confusing associated functions with methods
Lock-free data structures rely on hardware-level atomic instructions and explicit memory ordering constraints to coordinate threads without blocking via OS mutexes. By mastering Rust’s core::sync::atomic module, you can build low-latency concurrent primitives that avoid deadlocks and context-switch overhead.
The Memory Ordering Spectrum
Rust exposes six memory ordering variants via Ordering. Choosing the correct ordering dictates how CPU cores and compilers synchronize memory visibility:
Relaxed: Guarantees atomicity of the single operation, but provides zero synchronization or ordering guarantees with other memory accesses.Acquire: Used on load operations. Ensures that subsequent reads and writes in the current thread cannot be reordered before this load.Release: Used on store operations. Ensures that preceding reads and writes in the current thread cannot be reordered after this store.AcqRel: CombinesAcquireandReleasefor read-modify-write operations (e.g.,fetch_add,compare_exchange).SeqCst: Sequentially Consistent. Provides the strictest guarantees, enforcing a globally consistent program order for all threads.
Building a Lock-Free Stack (Treiber Stack)
The Treiber stack is a classical lock-free stack implemented using a singly linked list and an atomic pointer, managed via Compare-And-Swap (CAS) loops.
rustuse std::sync::atomic::{AtomicPtr, Ordering};
use std::ptr;
pub struct TreiberStack<T> {
head: AtomicPtr<Node<T>>,
}
struct Node<T> {
data: T,
next: *mut Node<T>,
}
impl<T> TreiberStack<T> {
pub fn new() -> Self {
Self {
head: AtomicPtr::new(ptr::null_mut()),
}
}
pub fn push(&self, data: T) {
let new_node = Box::into_raw(Box::new(Node {
data,
next: ptr::null_mut(),
}));
let mut current = self.head.load(Ordering::Relaxed);
loop {
// Unsafe update: point the new node to the current head
unsafe {
(*new_node).next = current;
}
// Attempt CAS. If head changed, `compare_exchange_weak` updates `current`
// and loops. Release ordering synchronizes the newly written node with
// any thread subsequently acquiring the head.
match self.head.compare_exchange_weak(
current,
new_node,
Ordering::Release,
Ordering::Relaxed,
) {
Ok(_) => break,
Err(actual) => current = actual,
}
}
}
pub fn pop(&self) -> Option<T> {
let mut current = self.head.load(Ordering::Acquire);
loop {
if current.is_null() {
return None;
}
let next = unsafe { (*current).next };
// Acquire ordering on success ensures we safely read the pointed-to node data.
match self.head.compare_exchange_weak(
current,
next,
Ordering::Acquire,
Ordering::Relaxed,
) {
Ok(_) => {
// Safety: We exclusively claimed this node via CAS. Convert back to Box to drop.
let boxed_node = unsafe { Box::from_raw(current) };
return Some(boxed_node.data);
}
Err(actual) => current = actual,
}
}
}
}
impl<T> Drop for TreiberStack<T> {
fn drop(&mut self) {
while self.pop().is_some() {}
}
}
fn main() {
use std::sync::Arc;
use std::thread;
let stack = Arc::new(TreiberStack::new());
let mut handles = vec![];
// Spawn 4 threads pushing items concurrently
for i in 0..4 {
let stack_clone = Arc::clone(&stack);
handles.push(thread::spawn(move || {
for j in 0..100 {
stack_clone.push(i * 100 + j);
}
}));
}
for h in handles {
h.join().unwrap();
}
// Drain the stack
let mut count = 0;
while stack.pop().is_some() {
count += 1;
}
println!("Successfully popped {} items from lock-free stack.", count);
}
Expected Output
textSuccessfully popped 400 items from lock-free stack.
Gotchas and Performance Considerations
- ABA Problem: In pure lock-free algorithms using raw pointers, a node can be popped, freed, and its memory reallocated for a new node. If the head pointer points to the same memory address, a CAS operation may succeed incorrectly. Production code typically requires tagged pointers or hazard pointers/epoch-based reclamation (e.g., crossbeam-epoch) to solve this.
- CAS Retry Loops: High contention on
compare_exchange_weakcauses CPU cache-coherency traffic (cache line bouncing). Under extreme contention, lock-free structures can perform worse than fine-grained mutexes. - Weak vs Strong CAS: Prefer
compare_exchange_weakovercompare_exchangeinside loops. On some architectures (like ARM),weakcan spuriously fail, which maps directly to the required loop iteration pattern anyway, yielding higher efficiency.
Key Takeaways
- Memory ordering decouples atomicity from synchronization visibility, allowing fine-tuned performance tuning at the cost of correctness complexity.
Acquire/Releasepairs form the bedrock of safe pointer handoffs between threads without incurring the performance penalty ofSeqCst.- Lock-free programming avoids OS-level thread blocking but introduces subtle concurrency bugs like the ABA problem and severe cache-coherency contention under load.
Modules in Rust
Modules help organize code into logical units and control privacy. Rust's module system includes modules, crates, and workspaces for large-scale code organization.
Basic Module Structure
rust// Declare a module
mod math {
// Public function
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
// Private function (default)
fn subtract(a: i32, b: i32) -> i32 {
a - b
}
// Nested module
pub mod advanced {
pub fn multiply(a: i32, b: i32) -> i32 {
a * b
}
}
}
fn main() {
// Use module functions
let sum = math::add(5, 3);
println!("5 + 3 = {}", sum);
let product = math::advanced::multiply(4, 5);
println!("4 * 5 = {}", product);
// This would error - subtract is private:
// math::subtract(10, 5);
}
Module Files and Directories
rust// File structure:
// src/
// main.rs
// math.rs
// math/
// advanced.rs
// In main.rs:
mod math; // This tells Rust to look for math.rs or math/mod.rs
fn main() {
math::add(5, 3);
math::advanced::multiply(4, 5);
}
// In math.rs:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub mod advanced; // Declare advanced module
// In math/advanced.rs:
pub fn multiply(a: i32, b: i32) -> i32 {
a * b
}
pub fn divide(a: i32, b: i32) -> Option<i32> {
if b == 0 {
None
} else {
Some(a / b)
}
}
Use Declarations and Imports
rustmod math {
pub mod basic {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
}
pub mod advanced {
pub fn multiply(a: i32, b: i32) -> i32 {
a * b
}
}
}
// Bring modules into scope
use math::basic::add;
use math::advanced::multiply;
// Rename imports
use math::advanced::multiply as mult;
// Import multiple items
use math::basic::{add, /* subtract */}; // subtract would be private
// Import all public items (use sparingly)
// use math::advanced::*;
fn main() {
// Now we can use the functions directly
let sum = add(5, 3);
let product = multiply(4, 5);
let also_product = mult(4, 5);
println!("Sum: {}, Product: {}, Also: {}", sum, product, also_product);
}
Privacy and Visibility
rustmod outer {
pub mod inner {
pub fn public_function() {
println!("This is public");
}
pub(crate) fn crate_visible() {
println!("Visible within crate");
}
fn private_function() {
println!("This is private");
}
// Function that uses private function
pub fn public_calls_private() {
println!("Public function calling private:");
private_function();
}
}
// Can access sibling module's private items
pub fn access_inner() {
inner::private_function(); // This works within same parent module
}
}
fn main() {
outer::inner::public_function();
outer::inner::public_calls_private();
outer::access_inner();
// These would error:
// outer::inner::private_function(); // private
// outer::inner::crate_visible(); // crate-visible, but we're in same crate
}
Advanced Module Patterns
rust// Prelude pattern for common imports
mod prelude {
pub use std::format;
pub use std::string::ToString;
pub use crate::math::*;
}
// Re-exporting (pub use)
mod math {
pub mod basic {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
}
// Re-export to make add available at math level
pub use basic::add;
}
// Now we can use math::add directly
use math::add;
// Inline modules with attributes
#[cfg(test)]
mod tests {
use super::*; // Import items from parent module
#[test]
fn test_addition() {
assert_eq!(add(2, 2), 4);
}
}
// Module with external code
#[path = "custom_path/math_utils.rs"]
mod math_utils;
fn main() {
let result = add(5, 3);
println!("5 + 3 = {}", result);
}
Crate Structure
rust// Typical crate structure:
// Cargo.toml
// src/
// lib.rs // Library crate root
// main.rs // Binary crate root
// math.rs // Module
// math/ // Module directory
// advanced.rs
// utils/ // Another module
// mod.rs // Module declaration file
// In lib.rs:
pub mod math;
pub mod utils;
// Re-export commonly used items
pub use math::basic::add;
pub use math::advanced::{multiply, divide};
// Library API
pub fn compute(a: i32, b: i32) -> i32 {
multiply(add(a, b), 2)
}
// In main.rs (if binary crate):
use my_crate::compute; // Assuming crate name is "my_crate"
fn main() {
let result = compute(3, 4);
println!("Result: {}", result); // (3+4)*2 = 14
}
Common Pitfalls
- Forgetting to make items
pubfor external use - Circular module dependencies
- Confusing module file structure (mod.rs vs named files)
- Overusing
pub usewhich can make API unclear - Not organizing code into modules as project grows
Rust’s trait system relies on strict coherence and orphan rules to guarantee that every type has a globally unique implementation for any given trait, enabling zero-cost polymorphism. When building high-performance systems, navigating these rules alongside nightly-only specialization allows you to override generic implementations with optimized, type-specific ones without runtime overhead.
The Orphan Rules and Coherence Fundamentals
Coherence requires that the compiler can always definitively resolve which trait implementation applies to a type. The orphan rule dictates that either the trait or the type implementing the trait must be local to the current crate. This prevents overlapping implementations across different dependencies.
rust// In crate A:
pub trait Render {
fn render(&self);
}
// ERROR: Violation of the orphan rule.
// Neither `Render` (external) nor `Vec<T>` (external) is local to this crate.
// impl<T> Render for Vec<T> {
// fn render(&self) {}
// }
To bypass this restriction when wrapping external types, use the newtype pattern. By wrapping an external type in a local struct, you establish local authority over the implementation.
rustpub struct MyVec<T>(pub Vec<T>);
impl<T: std::fmt::Debug> Render for MyVec<T> {
fn render(&self) {
println!("{:?}", self.0);
}
}
Specialization via Nightly Rust
By default, Rust prevents overlapping implementations (e.g., implementing a trait for T and simultaneously for u32) to avoid ambiguity. The unstable specialization feature flag relaxes this, letting you declare a default implementation that can be overridden by more specific types.
rust#![feature(specialization)]
pub trait FastSerialize {
fn serialize(&self) -> Vec<u8>;
}
// Generic fallback implementation
impl<T: ToString> FastSerialize for T {
default fn serialize(&self) -> Vec<u8> {
self.to_string().into_bytes()
}
}
// Highly optimized specialization for raw byte slices
impl FastSerialize for &[u8] {
fn serialize(&self) -> Vec<u8> {
// Zero-copy clone equivalent for raw data
(*self).to_vec()
}
}
Performance Considerations and Soundness Hazards
While specialization unlocks dramatic performance gains—such as bypassing serialization serialization loops for primitive byte arrays or utilizing memcpy for contiguous memory types—the feature remains unstable due to soundness holes involving associated types and lifetime variance.
When specializing, ensure that specialized implementations are strict subsets of the generic bounds. Violating this can lead to type confusion or compiler bugs in nightly toolchains. For stable Rust alternatives, rely on sealed traits combined with dispatch enums or conditional compilation via build scripts (build.rs).
Try It Yourself
Run the following code using a nightly toolchain (cargo +nightly run) to observe specialization in action:
rust#![feature(specialization)]
trait MetricRecorder {
fn record(&self) -> &'static str;
}
impl<T> MetricRecorder for T {
default fn record(&self) -> &'static str {
"generic_metric_path"
}
}
// Specialized path for high-frequency u64 counters
impl MetricRecorder for u64 {
fn record(&self) -> &'static str {
"optimized_counter_path"
}
}
fn main() {
let x: i32 = 42;
let y: u64 = 100;
println!("i32 metric: {}", x.record());
println!("u64 metric: {}", y.record());
}
Expected Output
```text i32 metric: generic_metric_path u64 metric: optimized_counter_path ```Key Takeaways
- The orphan rule dictates that either the trait or the implementing type must be defined locally within the current crate.
- The newtype pattern safely bridges external traits and external types without breaking coherence rules.
- Nightly specialization (
#![feature(specialization)]) allows generic implementations to be overridden by specific types for maximum performance. - Use specialization cautiously in production systems as underlying compiler rules remain unstable and prone to edge-case soundness bugs.
File Input/Output in Rust
Rust provides comprehensive file I/O operations through the std::fs and std::io modules. File operations return Result types that must be handled.
Basic File Operations
rustuse std::fs;
use std::io::{self, Write};
use std::path::Path;
fn main() -> io::Result<()> {
// Writing to a file
fs::write("example.txt", "Hello, File!\nThis is line 2\nNumber: 42")?;
println!("File written successfully");
// Reading from a file
let content = fs::read_to_string("example.txt")?;
println!("File content:\n{}", content);
// Reading as bytes
let bytes = fs::read("example.txt")?;
println!("File size: {} bytes", bytes.len());
// Check if file exists
if Path::new("example.txt").exists() {
println!("File exists");
}
Ok(())
}
Working with File Handles
rustuse std::fs::File;
use std::io::{BufReader, BufRead, BufWriter};
fn main() -> io::Result<()> {
// Open file for writing
let mut file = File::create("output.txt")?;
writeln!(&mut file, "Hello, File!")?;
writeln!(&mut file, "This is line 2")?;
file.write_all(b"Binary data\n")?;
// Open file for reading
let file = File::open("output.txt")?;
let reader = BufReader::new(file);
// Read line by line
for line in reader.lines() {
println!("{}", line?);
}
// Append to file
let mut file = fs::OpenOptions::new()
.append(true)
.open("output.txt")?;
writeln!(&mut file, "Appended line")?;
Ok(())
}
Different File Opening Modes
rustuse std::fs::OpenOptions;
fn main() -> io::Result<()> {
// Various file opening modes
let file1 = File::create("new_file.txt")?; // Create or truncate
let file2 = File::open("existing_file.txt")?; // Read only
// Using OpenOptions for more control
let file3 = OpenOptions::new()
.read(true)
.write(true)
.create(true) // Create if doesn't exist
.open("data.txt")?;
let file4 = OpenOptions::new()
.append(true)
.open("log.txt")?; // Append mode
let file5 = OpenOptions::new()
.write(true)
.create_new(true) // Only create if doesn't exist
.open("brand_new.txt")?;
// Example: Append to log file
let mut log_file = OpenOptions::new()
.create(true)
.append(true)
.open("application.log")?;
writeln!(&mut log_file, "New log entry")?;
Ok(())
}
Reading Different Data Types
rustuse std::io::{BufRead, BufReader};
fn read_mixed_data() -> io::Result<()> {
// Write mixed data
let data = "John Doe 25 85.5\nJane Smith 30 92.0\n";
fs::write("data.txt", data)?;
// Read and parse mixed data types
let file = File::open("data.txt")?;
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line?;
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() == 4 {
let first_name = parts[0];
let last_name = parts[1];
let age: u32 = parts[2].parse().unwrap_or(0);
let score: f64 = parts[3].parse().unwrap_or(0.0);
println!("{} {}, Age: {}, Score: {}",
first_name, last_name, age, score);
}
}
Ok(())
}
fn read_structured_data() -> io::Result<()> {
// Using serde for structured data (with serde_json crate)
// #[derive(Serialize, Deserialize)]
// struct Person {
// name: String,
// age: u32,
// scores: Vec<f64>,
// }
// let person = Person { ... };
// let json = serde_json::to_string(&person)?;
// fs::write("person.json", json)?;
// let content = fs::read_to_string("person.json")?;
// let person: Person = serde_json::from_str(&content)?;
Ok(())
}
File System Operations
rustuse std::fs;
use std::path::Path;
fn file_system_operations() -> io::Result<()> {
// Create directory
fs::create_dir("my_dir")?;
fs::create_dir_all("parent/child/grandchild")?; // Create all directories in path
// Check file metadata
let metadata = fs::metadata("example.txt")?;
println!("File size: {} bytes", metadata.len());
println!("Is file: {}", metadata.is_file());
println!("Is directory: {}", metadata.is_dir());
// Copy file
fs::copy("example.txt", "example_copy.txt")?;
// Rename/move file
fs::rename("example_copy.txt", "renamed.txt")?;
// Remove file
fs::remove_file("renamed.txt")?;
// Remove directory (must be empty)
fs::remove_dir("my_dir")?;
// Remove directory and all contents
fs::remove_dir_all("parent")?;
// List directory contents
for entry in fs::read_dir(".")? {
let entry = entry?;
let path = entry.path();
if path.is_file() {
println!("File: {}", path.display());
} else if path.is_dir() {
println!("Directory: {}", path.display());
}
}
Ok(())
}
Error Handling in File I/O
rustuse std::io;
fn robust_file_operations() -> io::Result<()> {
// Handling file not found gracefully
let content = fs::read_to_string("nonexistent.txt")
.unwrap_or_else(|_| "File not found".to_string());
println!("Content: {}", content);
// Using match for different error cases
match fs::read_to_string("important.txt") {
Ok(content) => println!("File content: {}", content),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
println!("File not found, creating default...");
fs::write("important.txt", "Default content")?;
}
Err(e) => return Err(e), // Propagate other errors
}
// Using Result combinators
let result = fs::read_to_string("config.txt")
.and_then(|content| {
if content.is_empty() {
Err(io::Error::new(io::ErrorKind::InvalidData, "Empty file"))
} else {
Ok(content)
}
});
match result {
Ok(config) => println!("Config: {}", config),
Err(e) => println!("Error reading config: {}", e),
}
Ok(())
}
// Function that returns Result
fn read_config() -> io::Result<String> {
let content = fs::read_to_string("config.txt")?;
if content.trim().is_empty() {
return Err(io::Error::new(io::ErrorKind::InvalidData, "Empty config"));
}
Ok(content)
}
Common Pitfalls
- Not handling I/O errors (using
unwrap()instead of proper error handling) - Forgetting that file paths are relative to current working directory
- Not closing files explicitly (Rust does this automatically, but be mindful of scope)
- Assuming files exist without checking
- Not using buffered I/O for large files
Enforcing structural domain boundaries across a large Rust codebase often requires moving beyond standard cargo lints into custom compiler plugins that analyze the Abstract Syntax Tree (AST) via the unstable rustc-private API. By tapping directly into the compiler driver infrastructure, you can programmatically block undesirable architectural patterns (such as domain models referencing database layers directly) during compilation.
The Compiler Driver and Lints Setup
Building a custom linter requires compiling as a toolchain-dependent binary or driver that links against rustc_driver. Because rustc-private APIs are unstable and tightly coupled to specific nightly compiler versions, your Cargo.toml must declare dependencies with the rustc-private flag.
toml[package]
name = "arch_lints"
version = "0.1.0"
edition = "2021"
[dependencies]
# Requires nightly toolchain and RUSTC_BOOTSTRAP=1
To implement a custom lint, you define a struct that implements rustc_lint::LintPass, register it using the declare_lint_pass! macro, and hook into AST traversal methods like check_item or check_expr.
rust#![feature(rustc_private)]
extern crate rustc_ast;
extern crate rustc_driver;
extern crate rustc_errors;
extern crate rustc_hir;
extern crate rustc_lint;
extern crate rustc_session;
use rustc_hir::{Item, ItemKind, Path};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_session::{declare_lint_pass, declare_tool_lint};
declare_tool_lint! {
pub arch_lints::RESTRICTED_DOMAIN_IMPORT,
Deny,
"domain layer must not import infrastructure layer directly"
}
declare_lint_pass!(DomainBoundaryLint => [RESTRICTED_DOMAIN_IMPORT]);
impl<'tcx> LateLintPass<'tcx> for DomainBoundaryLint {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: Item<'tcx>) {
// Enforce that modules named 'domain' never use paths containing 'infrastructure'
if let ItemKind::Use(path, _is_glob) = item.kind {
let path_str = path_to_string(path);
if in_domain_module(cx, item.hir_id()) && path_str.contains("infrastructure") {
cx.span_lint(
RESTRICTED_DOMAIN_IMPORT,
item.span,
|diag| {
diag.builder.set_primary_message(
"Architectural violation: Domain layer imports Infrastructure"
);
diag.help("Domain logic must remain pure; depend on traits instead of concrete infra
Standard Library Introduction
Rust's standard library (std) provides essential functionality for Rust programs. It includes types for I/O, collections, concurrency, and many utilities.
Key Standard Library Components
rust// Commonly used standard library modules
use std::collections::{HashMap, HashSet, VecDeque};
use std::io::{self, Read, Write, BufRead};
use std::fs;
use std::path::Path;
use std::time::{Duration, Instant};
use std::thread;
use std::sync::{Arc, Mutex};
fn main() {
// Option and Result - fundamental for error handling
let some_value: Option<i32> = Some(42);
let none_value: Option<i32> = None;
let ok_result: Result<i32, &str> = Ok(42);
let err_result: Result<i32, &str> = Err("Something went wrong");
// String and str
let owned_string = String::from("Hello");
let string_slice: &str = "World";
// Vectors and arrays
let vector = vec![1, 2, 3, 4, 5];
let array = [1, 2, 3, 4, 5];
println!("Standard library types are ready to use!");
}
Essential Traits and Types
rustuse std::fmt;
use std::ops::Add;
// Common traits
#[derive(Debug, Clone, PartialEq, Eq)] // Automatically implement traits
struct Point {
x: i32,
y: i32,
}
// Manual implementation of Display trait
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
// Implementing operator overloading
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
println!("Debug: {:?}", p1); // Uses Debug trait
println!("Display: {}", p1); // Uses Display trait
println!("Sum: {}", p1 + p2); // Uses Add trait
// Clone trait
let p3 = p1.clone();
println!("Cloned: {:?}", p3);
// PartialEq trait
println!("Equal: {}", p1 == p3); // true
}
Common Utility Functions
rustuse std::mem;
fn utility_functions() {
// Memory utilities
let x = 42;
println!("Size of i32: {}", mem::size_of::<i32>());
println!("Size of String: {}", mem::size_of::<String>());
// Take ownership and return it (moves value)
let s = String::from("hello");
let same_s = mem::take(&mut s.clone()); // Note: needs mutable reference
// Replace value
let mut v = vec![1, 2, 3];
let old_v = mem::replace(&mut v, vec![4, 5, 6]);
println!("Old: {:?}, New: {:?}", old_v, v);
// Convert to raw parts
let s = String::from("hello");
let (ptr, len, cap) = s.into_raw_parts();
// Can reconstruct string from raw parts
let _reconstructed = unsafe { String::from_raw_parts(ptr, len, cap) };
}
// Environment and program information
fn program_info() {
// Command line arguments
let args: Vec<String> = std::env::args().collect();
println!("Program name: {}", args[0]);
// Environment variables
if let Ok(path) = std::env::var("PATH") {
println!("PATH: {}", path);
}
// Current directory
if let Ok(current_dir) = std::env::current_dir() {
println!("Current directory: {}", current_dir.display());
}
}
Error Handling Utilities
rustuse std::error::Error;
use std::fmt;
#[derive(Debug)]
struct CustomError {
message: String,
}
impl fmt::Display for CustomError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "CustomError: {}", self.message)
}
}
impl Error for CustomError {}
fn might_fail(should_fail: bool) -> Result<String, CustomError> {
if should_fail {
Err(CustomError {
message: "It failed!".to_string(),
})
} else {
Ok("Success!".to_string())
}
}
fn error_handling_examples() -> Result<(), Box<dyn Error>> {
// Using ? operator for error propagation
let content = std::fs::read_to_string("file.txt")?;
// Converting between error types
let number = "42".parse::<i32>()
.map_err(|e| CustomError { message: e.to_string() })?;
// Combinator methods
let result = might_fail(false)
.and_then(|s| Ok(s + " And more!"))
.or_else(|_| Ok("Default value".to_string()));
println!("Result: {}", result?);
Ok(())
}
fn main() -> Result<(), Box<dyn Error>> {
error_handling_examples()?;
Ok(())
}
Standard Library Organization
rust/*
Standard Library Organization:
core/ - No-std components (always available)
alloc/ - Heap allocation types (needs allocator)
std/ - Full standard library
Main modules:
- std::collections - HashMap, Vec, String, etc.
- std::io - Input/output operations
- std::fs - File system operations
- std::path - Path manipulation
- std::env - Environment variables
- std::process - Process management
- std::thread - Concurrency
- std::sync - Synchronization primitives
- std::time - Time operations
- std::net - Networking
- std::fmt - Formatting
- std::default - Default values
- std::convert - Type conversions
- std::ops - Operator overloading
- std::cmp - Comparisons
*/
// No-std programming (for embedded systems)
// #![no_std]
// use core::prelude::v1::*;
fn main() {
println!("Standard library provides batteries-included functionality");
}
Common Pitfalls
- Not understanding the difference between core, alloc, and std
- Forgetting to handle Result and Option types properly
- Using unwrap() in production code instead of proper error handling
- Not leveraging standard library traits for custom types
- Reimplementing functionality that's already in the standard library
An actor runtime isolates state and processes concurrent messages sequentially via asynchronous message-passing, eliminating shared-memory data races entirely.
Architecture of a Custom Actor System
To build an actor runtime from scratch, we need three core abstractions:
Message: A trait representing payloads sent to actors.Actor: A trait defining an entity’s lifecycle and message-handling logic.Addr<A>: A handle used by callers to dispatch messages to an actor’s mailbox without blocking.
rustuse tokio::sync::{mpsc, oneshot};
use std::future::Future;
use std::pin::Pin;
pub trait Message: Send + 'static {
type Result: Send + 'static;
}
pub trait Actor: Send + Sized + 'static {
fn handle(
&mut self,
msg: impl Message,
) -> Pin<Box<dyn Future<Output = <impl Message as Message>::Result> + Send>>;
}
However, dynamic dispatch over associated types in traits requires a type-erased message wrapper or a unified message enum. For a robust, high-throughput runtime, we use a message envelope pattern with tokio::sync::mpsc channels and oneshot channels for request-reply semantics.
Implementing the Runtime Engine
Let’s implement a complete, thread-safe actor runtime using Tokio’s underlying task scheduler. We use an enum or trait-object message box to queue tasks inside an unbounded or bounded Tokio channel.
rustuse tokio::sync::{mpsc, oneshot};
// Define an envelope to handle message passing and response delivery
enum Envelope {
// Example message: Increment counter and return new value
Increment(usize, oneshot::Sender<usize>),
Get(oneshot::Sender<usize>),
}
pub struct CounterActor {
count: usize,
receiver: mpsc::Receiver<Envelope>,
}
pub struct CounterAddr {
sender: mpsc::Sender<Envelope>,
}
impl CounterAddr {
pub async fn increment(&self, val: usize) -> usize {
let (tx, rx) = oneshot::channel();
self.sender.send(Envelope::Increment(val, tx)).await.unwrap();
rx.await.unwrap()
}
pub async fn get(&self) -> usize {
let (tx, rx) = oneshot::channel();
self.sender.send(Envelope::Get(tx)).await.unwrap();
rx.await.unwrap()
}
}
impl CounterActor {
pub fn new(capacity: usize) -> (Self, CounterAddr) {
let (sender, receiver) = mpsc::channel(capacity);
(
Self { count: 0, receiver },
CounterAddr { sender },
)
}
pub async fn run(mut self) {
while let Some(msg) = self.receiver.recv().await {
match msg {
Envelope::Increment(val, respond_to) => {
self.count += val;
let _ = respond_to.send(self.count);
}
Envelope::Get(respond_to) => {
let _ = respond_to.send(self.count);
}
}
}
}
}
#[tokio::main]
async fn main() {
let (actor, addr) = CounterActor::new(32);
// Spawn the actor loop onto the Tokio runtime
tokio::spawn(actor.run());
addr.increment(5).await;
addr.increment(10).await;
let current = addr.get().await;
println!("Final Counter Value: {}", current);
}
Expected Output
textFinal Counter Value: 15
Performance Considerations & Gotchas
- Mailbox Bounding: Always prefer bounded channels (
mpsc::channel(n)) over unbounded ones (mpsc::unbounded_channel()) to prevent runaway memory consumption under backpressure mismatches. - Deadlocks: Avoid synchronous blocking calls (e.g.,
.blocking_recv(),std::thread::sleep) inside actor handlers. This starves the Tokio worker thread pool. - Panic Isolation: If an actor panics inside its message loop, the underlying Tokio task dies. Wrap message execution in
std::panic::AssertUnwindSafeand catch panics if fault-tolerant supervision trees are required.
Key Takeaways
- Actors eliminate shared-state synchronization overhead by encapsulating state behind an asynchronous message queue.
- Tokio’s
mpscandoneshotchannels form the fundamental primitive for asynchronous request-reply actor messaging. - Explicit lifecycle management via background task spawning (
tokio::spawn) keeps actor execution non-blocking and concurrent.
Standard Library Collections
Rust's standard library provides efficient, generic collections for storing and manipulating data. Each collection has different performance characteristics and use cases.
Vector (Vec<T>)
rustfn vector_examples() {
// Creating vectors
let mut vec1 = Vec::new();
vec1.push(1);
vec1.push(2);
vec1.push(3);
let vec2 = vec![1, 2, 3, 4, 5]; // Macro syntax
let vec3 = Vec::with_capacity(10); // Pre-allocate
// Accessing elements
println!("First: {}", vec2[0]); // Panics if out of bounds
println!("First: {:?}", vec2.get(0)); // Returns Option
// Iteration
for element in &vec2 { // Borrow - doesn't consume
println!("Element: {}", element);
}
for element in vec2 { // Consumes vector
println!("Element: {}", element);
}
// vec2 is no longer usable here
// Common operations
let mut numbers = vec![1, 2, 3, 4, 5];
numbers.pop(); // Remove last
numbers.insert(2, 99); // Insert at index
numbers.remove(1); // Remove at index
numbers.retain(|&x| x % 2 == 0); // Keep only even numbers
println!("Modified: {:?}", numbers);
}
String and String Slices
rustfn string_examples() {
// String (owned, growable)
let mut s1 = String::new();
s1.push_str("Hello");
s1.push(' ');
s1.push_str("World");
let s2 = "Initial content".to_string();
let s3 = String::from("From string literal");
// String slices (&str) - borrowed
let literal = "Hello World"; // This is &str
let slice = &s1[0..5]; // "Hello"
// Conversion between String and &str
let owned: String = slice.to_string();
let borrowed: &str = &owned;
// String operations
let text = String::from("Hello Rust!");
println!("Length: {}", text.len()); // Number of bytes
println!("Chars count: {}", text.chars().count()); // Number of characters
// Splitting
for word in text.split_whitespace() {
println!("Word: {}", word);
}
// Concatenation
let s4 = s1 + " " + &s2; // Note: s1 is moved
let s5 = format!("{} {}", s3, "concatenated");
println!("s4: {}, s5: {}", s4, s5);
}
HashMap and HashSet
rustuse std::collections::{HashMap, HashSet};
fn hash_examples() {
// HashMap - key-value storage
let mut scores = HashMap::new();
scores.insert("Alice", 10);
scores.insert("Bob", 20);
scores.insert("Charlie", 30);
// Accessing values
if let Some(score) = scores.get("Alice") {
println!("Alice's score: {}", score);
}
// Update values
scores.insert("Alice", 25); // Overwrite
scores.entry("Bob").or_insert(50); // Insert if not exists
scores.entry("David").or_insert(40); // Insert new
// Iteration
for (name, score) in &scores {
println!("{}: {}", name, score);
}
// HashSet - unique values
let mut set1 = HashSet::new();
set1.insert(1);
set1.insert(2);
set1.insert(3);
set1.insert(2); // Duplicate - ignored
let set2: HashSet<_> = [3, 4, 5].iter().cloned().collect();
// Set operations
println!("Union: {:?}", set1.union(&set2));
println!("Intersection: {:?}", set1.intersection(&set2));
println!("Difference: {:?}", set1.difference(&set2));
println!("Set1: {:?}", set1);
}
Other Collections
rustuse std::collections::{VecDeque, BinaryHeap, BTreeMap, BTreeSet};
fn other_collections() {
// VecDeque - double-ended queue
let mut deque = VecDeque::new();
deque.push_back(1); // Add to end
deque.push_front(0); // Add to front
deque.pop_back(); // Remove from end
deque.pop_front(); // Remove from front
// BinaryHeap - priority queue (max-heap by default)
let mut heap = BinaryHeap::new();
heap.push(3);
heap.push(1);
heap.push(5);
heap.push(2);
while let Some(max) = heap.pop() {
println!("Max: {}", max); // 5, 3, 2, 1
}
// BTreeMap - sorted map
let mut btree = BTreeMap::new();
btree.insert(3, "three");
btree.insert(1, "one");
btree.insert(2, "two");
// Keys are sorted
for (key, value) in &btree {
println!("{}: {}", key, value); // 1, 2, 3
}
// BTreeSet - sorted set
let mut btree_set = BTreeSet::new();
btree_set.insert(3);
btree_set.insert(1);
btree_set.insert(2);
println!("BTreeSet: {:?}", btree_set); // {1, 2, 3}
}
Collection Performance Characteristics
rust/*
Collection | Insert | Access | Search | Remove | Use Case
--------------|--------|--------|--------|--------|---------
Vec<T> | O(1)* | O(1) | O(n) | O(n) | General purpose, indexing
VecDeque<T> | O(1)* | O(1) | O(n) | O(n) | Queue, double-ended operations
LinkedList<T> | O(1) | O(n) | O(n) | O(1) | Frequent insert/remove at ends
HashMap<K,V> | O(1)* | O(1)* | O(1)* | O(1)* | Key-value lookups
BTreeMap<K,V> | O(log n)|O(log n)|O(log n)|O(log n)| Sorted key-value
HashSet<T> | O(1)* | O(1)* | O(1)* | O(1)* | Unique elements, membership
BTreeSet<T> | O(log n)|O(log n)|O(log n)|O(log n)| Sorted unique elements
BinaryHeap<T> | O(log n)|O(1) | O(n) | O(log n)| Priority queue
* = amortized constant time, depends on hash distribution
*/
fn performance_considerations() {
// Choose the right collection for your use case
// Vec: When you need indexing or are mostly adding to the end
let mut vec = Vec::with_capacity(1000); // Pre-allocate if size known
// HashMap: When you need fast key-based lookups
use std::collections::HashMap;
let mut map = HashMap::with_capacity(1000);
// VecDeque: When you need queue-like behavior (FIFO)
use std::collections::VecDeque;
let mut queue = VecDeque::new();
// BinaryHeap: When you need priority-based access
use std::collections::BinaryHeap;
let mut heap = BinaryHeap::new();
println!("Choose collections based on your access patterns");
}
Collection Methods and Patterns
rustfn collection_methods() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Functional programming style
let doubled: Vec<i32> = numbers.iter().map(|&x| x * 2).collect();
let evens: Vec<&i32> = numbers.iter().filter(|&&x| x % 2 == 0).collect();
let sum: i32 = numbers.iter().sum();
println!("Doubled: {:?}", doubled);
println!("Evens: {:?}", evens);
println!("Sum: {}", sum);
// Chaining operations
let result: Vec<i32> = numbers
.iter()
.filter(|&&x| x > 5)
.map(|&x| x * 3)
.collect();
println!("Filtered and mapped: {:?}", result);
// Using collect with type inference
let squared: Vec<i32> = numbers.iter().map(|&x| x * x).collect();
let as_hashset: HashSet<i32> = numbers.iter().cloned().collect();
let as_string: String = numbers.iter().map(|x| x.to_string()).collect();
// Partitioning
let (even, odd): (Vec<i32>, Vec<i32>) = numbers
.into_iter()
.partition(|&x| x % 2 == 0);
println!("Even: {:?}, Odd: {:?}", even, odd);
}
Common Pitfalls
- Using
[]indexing that can panic instead ofget() - Not pre-allocating capacity when size is known for Vec/HashMap
- Forgetting that HashMap keys need to implement Hash and Eq
- Using the wrong collection for the access pattern
- Not handling the possibility of hash collisions in performance-critical code
Lifetime variance defines how subtyping between lifetimes affects subtyping between complex types that contain those lifetimes, dictating whether a reference can safely be substituted for a longer or shorter-lived one. Mastering variance is essential for designing zero-cost, self-referential, or highly concurrent data structures without fighting the borrow checker.
Variance Classifications in Rust
Variance describes the relationship between subtyping of components and the subtyping of the types containing them. A lifetime 'a outlives 'b (written 'a: 'b), meaning 'a is longer and can be substituted anywhere a shorter lifetime 'b is expected.
Rust determines variance automatically for type parameters based on where and how they appear in a struct or enum definition:
- Covariant: If a type parameter is covariant (like
&'a T), a longer lifetime can be safely substituted for a shorter one (&'a Tcan be used
Standard Library Iterators
Iterators are a fundamental abstraction in Rust for processing sequences of elements. They are lazy, composable, and often zero-cost.
Basic Iterator Usage
rustfn basic_iterator_examples() {
let numbers = vec![1, 2, 3, 4, 5];
// Creating iterators
let iter1 = numbers.iter(); // Immutable references
let iter2 = numbers.iter_mut(); // Mutable references
let iter3 = numbers.into_iter(); // Takes ownership (consumes)
// Using iterators
for number in numbers.iter() {
println!("Number: {}", number);
}
// Collecting into new collections
let doubled: Vec<i32> = numbers.iter().map(|&x| x * 2).collect();
let as_string: String = numbers.iter().map(|x| x.to_string()).collect();
println!("Doubled: {:?}", doubled);
println!("As string: {}", as_string);
// numbers is still usable here because we used iter()
}
Common Iterator Adaptors
rustfn iterator_adaptors() {
let numbers = 1..=10; // Range is an iterator
// map - transform each element
let squares: Vec<i32> = numbers.clone().map(|x| x * x).collect();
// filter - keep elements that satisfy predicate
let evens: Vec<i32> = numbers.clone().filter(|x| x % 2 == 0).collect();
// take - take first n elements
let first_three: Vec<i32> = numbers.clone().take(3).collect();
// skip - skip first n elements
let after_three: Vec<i32> = numbers.clone().skip(3).collect();
// zip - combine two iterators
let pairs: Vec<(i32, i32)> = numbers.clone()
.zip(numbers.clone().map(|x| x * 2))
.collect();
// chain - combine two iterators sequentially
let chained: Vec<i32> = (1..=3).chain(7..=10).collect();
// enumerate - get (index, value) pairs
for (i, value) in numbers.clone().enumerate() {
println!("Index: {}, Value: {}", i, value);
}
println!("Squares: {:?}", squares);
println!("Evens: {:?}", evens);
println!("First three: {:?}", first_three);
println!("Pairs: {:?}", pairs);
println!("Chained: {:?}", chained);
}
Consumer Methods
rustfn consumer_methods() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// sum - sum all elements
let total: i32 = numbers.iter().sum();
// product - multiply all elements
let product: i32 = numbers.iter().product();
// count - count elements
let count = numbers.iter().count();
// min/max - find minimum/maximum
let min = numbers.iter().min();
let max = numbers.iter().max();
// find - find first element matching predicate
let first_even = numbers.iter().find(|&&x| x % 2 == 0);
// position - find position of element
let pos_of_5 = numbers.iter().position(|&&x| x == 5);
// all/any - check if all/any elements satisfy predicate
let all_positive = numbers.iter().all(|&&x| x > 0);
let any_negative = numbers.iter().any(|&&x| x < 0);
// fold - accumulate values
let sum_fold = numbers.iter().fold(0, |acc, &x| acc + x);
// for_each - execute closure for each element
numbers.iter().for_each(|x| println!("Value: {}", x));
println!("Total: {}, Count: {}", total, count);
println!("Min: {:?}, Max: {:?}", min, max);
println!("First even: {:?}", first_even);
println!("All positive: {}", all_positive);
println!("Sum with fold: {}", sum_fold);
}
Creating Custom Iterators
ruststruct Counter {
current: u32,
max: u32,
}
impl Counter {
fn new(max: u32) -> Counter {
Counter { current: 0, max }
}
}
// Implement Iterator trait
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.current < self.max {
self.current += 1;
Some(self.current)
} else {
None
}
}
}
// Implementing IntoIterator for custom types
struct MyCollection {
data: Vec<i32>,
}
impl IntoIterator for MyCollection {
type Item = i32;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.data.into_iter()
}
}
fn custom_iterator_examples() {
// Using custom iterator
let counter = Counter::new(5);
for num in counter {
println!("Counter: {}", num); // 1, 2, 3, 4, 5
}
// Using iterator methods on custom iterator
let sum: u32 = Counter::new(5).sum();
let doubled: Vec<u32> = Counter::new(3).map(|x| x * 2).collect();
println!("Sum: {}", sum); // 15
println!("Doubled: {:?}", doubled); // [2, 4, 6]
// MyCollection with IntoIterator
let collection = MyCollection { data: vec![1, 2, 3] };
for value in collection { // Uses into_iter automatically
println!("Value: {}", value);
}
}
Advanced Iterator Patterns
rustuse std::iter::{once, repeat, empty};
fn advanced_iterator_patterns() {
// Creating iterators from functions
let ones = repeat(1).take(5); // 1, 1, 1, 1, 1
let empty_iter = empty::<i32>(); // No elements
let single = once(42); // Single element: 42
// Cycle - repeat iterator endlessly
let cycled: Vec<i32> = vec![1, 2, 3].into_iter().cycle().take(7).collect();
println!("Cycled: {:?}", cycled); // [1, 2, 3, 1, 2, 3, 1]
// Windows and chunks for slices
let data = [1, 2, 3, 4, 5];
for window in data.windows(3) {
println!("Window: {:?}", window); // [1,2,3], [2,3,4], [3,4,5]
}
for chunk in data.chunks(2) {
println!("Chunk: {:?}", chunk); // [1,2], [3,4], [5]
}
// Peekable iterator (look ahead without consuming)
let mut peekable = data.iter().peekable();
while let Some(&item) = peekable.peek() {
println!("Next item will be: {}", item);
peekable.next(); // Actually consume it
}
// Inspect - debug without affecting iterator
let sum: i32 = data.iter()
.inspect(|x| println!("Processing: {}", x))
.map(|&x| x * 2)
.inspect(|x| println!("Doubled: {}", x))
.sum();
println!("Final sum: {}", sum);
}
Iterator Performance
rustfn iterator_performance() {
// Iterators are often zero-cost abstractions
// The generated assembly can be as efficient as hand-written loops
let numbers: Vec<i32> = (1..=1000).collect();
// This iterator chain...
let sum: i32 = numbers
.iter()
.filter(|&&x| x % 2 == 0)
.map(|&x| x * x)
.sum();
// ...is as efficient as this manual loop:
let mut manual_sum = 0;
for &x in &numbers {
if x % 2 == 0 {
manual_sum += x * x;
}
}
assert_eq!(sum, manual_sum);
// Lazy evaluation - nothing happens until you consume
let lazy_iter = (1..)
.map(|x| x * 2)
.filter(|x| x % 3 == 0)
.take(5);
// The above doesn't do any work until we collect
let result: Vec<i32> = lazy_iter.collect();
println!("Lazy result: {:?}", result); // [6, 12, 18, 24, 30]
// Using size hints for optimization
let iter = (1..100).filter(|x| x % 2 == 0);
println!("Size hint: {:?}", iter.size_hint()); // (0, Some(99))
}
// Benchmarking iterator vs loop (conceptual)
/*
In practice, iterators are often as fast or faster than loops because:
- They can be optimized better by the compiler
- They avoid bounds checks in many cases
- They enable vectorization opportunities
*/
Common Pitfalls
- Forgetting to consume iterators (they're lazy)
- Using
into_iter()when you meantiter() - Not leveraging iterator adaptors and going back to loops unnecessarily
- Creating intermediate collections when not needed
- Ignoring iterator size hints for optimization opportunities
Structs in Rust
Structs are custom data types that let you name and package together multiple related values. Rust has three struct variants: classic, tuple, and unit structs.
Basic Struct Definition and Usage
rust// Classic struct with named fields
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
// Tuple struct (like a named tuple)
struct Color(i32, i32, i32);
// Unit struct (no fields)
struct Marker;
fn main() {
// Creating struct instances
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
// Accessing fields
println!("User: {}, Email: {}", user1.username, user1.email);
// Creating mutable struct
let mut user2 = User {
email: String::from("another@example.com"),
username: String::from("anotherusername"),
active: true,
sign_in_count: 1,
};
user2.sign_in_count = 2; // Can modify because user2 is mutable
// Tuple struct usage
let black = Color(0, 0, 0);
println!("Black: ({}, {}, {})", black.0, black.1, black.2);
// Unit struct usage
let marker = Marker;
}
Struct Methods and Associated Functions
ruststruct Rectangle {
width: u32,
height: u32,
}
// Implementation block for methods
impl Rectangle {
// Method - takes &self (immutable reference to self)
fn area(&self) -> u32 {
self.width * self.height
}
// Method - takes &mut self (mutable reference)
fn scale(&mut self, factor: u32) {
self.width *= factor;
self.height *= factor;
}
// Method - takes self (consumes the struct)
fn into_tuple(self) -> (u32, u32) {
(self.width, self.height)
}
// Associated function (no self parameter) - like static method
fn square(size: u32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}
// Method with parameters
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
let mut rect = Rectangle { width: 30, height: 50 };
// Call methods
println!("Area: {}", rect.area());
rect.scale(2);
println!("Scaled area: {}", rect.area());
let small = Rectangle { width: 10, height: 10 };
println!("Can hold small? {}", rect.can_hold(&small));
// Call associated function
let square = Rectangle::square(25);
println!("Square area: {}", square.area());
// Consume the struct
let dimensions = rect.into_tuple();
println!("Dimensions: {}x{}", dimensions.0, dimensions.1);
// rect is no longer usable here
}
Struct Update Syntax and Patterns
ruststruct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
fn struct_patterns() {
let user1 = User {
email: String::from("user1@example.com"),
username: String::from("user1"),
active: true,
sign_in_count: 1,
};
// Struct update syntax
let user2 = User {
email: String::from("user2@example.com"),
username: String::from("user2"),
..user1 // Use the rest of the fields from user1
};
// Destructuring structs
let User { username, email, active, .. } = user2;
println!("User: {}, Email: {}, Active: {}", username, email, active);
// Destructuring in function parameters
fn print_user_info(User { username, email, .. }: &User) {
println!("{} - {}", username, email);
}
print_user_info(&user1);
// Pattern matching with structs
match user1 {
User { username, active: true, .. } => {
println!("Active user: {}", username);
}
User { username, active: false, .. } => {
println!("Inactive user: {}", username);
}
}
}
Generic Structs
rust// Generic struct with one type parameter
struct Point<T> {
x: T,
y: T,
}
// Generic struct with multiple type parameters
struct Pair<T, U> {
first: T,
second: U,
}
// Implementation for generic struct
impl<T> Point<T> {
fn new(x: T, y: T) -> Point<T> {
Point { x, y }
}
fn x(&self) -> &T {
&self.x
}
}
// Implementation with trait bounds
impl<T: PartialEq> Point<T> {
fn is_equal(&self, other: &Point<T>) -> bool {
self.x == other.x && self.y == other.y
}
}
// Specialized implementation for specific type
impl Point<f64> {
fn distance_from_origin(&self) -> f64 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
fn main() {
// Using generic structs with different types
let integer_point = Point { x: 5, y: 10 };
let float_point = Point { x: 1.0, y: 4.0 };
let string_pair = Pair { first: "hello", second: "world" };
println!("Integer point: ({}, {})", integer_point.x, integer_point.y);
println!("Float point distance: {}", float_point.distance_from_origin());
println!("String pair: {} {}", string_pair.first, string_pair.second);
}
Advanced Struct Patterns
rustuse std::fmt;
// Struct with lifetime parameters
struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
fn new(text: &'a str) -> ImportantExcerpt<'a> {
ImportantExcerpt {
part: text,
}
}
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention please: {}", announcement);
self.part
}
}
// Newtype pattern (wrapper around existing type)
struct Meters(f64);
impl Meters {
fn to_kilometers(&self) -> f64 {
self.0 / 1000.0
}
}
// Implementing traits for structs
impl fmt::Display for Meters {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} meters", self.0)
}
}
fn advanced_struct_examples() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().expect("Could not find a '.'");
let excerpt = ImportantExcerpt::new(first_sentence);
println!("Excerpt: {}", excerpt.part);
let distance = Meters(5000.0);
println!("{} = {} kilometers", distance, distance.to_kilometers());
// Builder pattern for complex struct construction
let user = UserBuilder::new()
.username("john_doe")
.email("john@example.com")
.build();
println!("Built user: {}", user.username);
}
// Builder pattern implementation
struct UserBuilder {
username: Option<String>,
email: Option<String>,
}
impl UserBuilder {
fn new() -> UserBuilder {
UserBuilder {
username: None,
email: None,
}
}
fn username(mut self, username: &str) -> UserBuilder {
self.username = Some(username.to_string());
self
}
fn email(mut self, email: &str) -> UserBuilder {
self.email = Some(email.to_string());
self
}
fn build(self) -> User {
User {
username: self.username.unwrap_or_else(|| "unknown".to_string()),
email: self.email.unwrap_or_else(|| "unknown@example.com".to_string()),
sign_in_count: 0,
active: true,
}
}
}
Common Pitfalls
- Forgetting to make struct fields public when needed (
pub) - Confusing when to use
&selfvsselfin methods - Not handling lifetimes properly in structs with references
- Overusing generic parameters when not needed
- Forgetting to derive or implement common traits (Debug, Clone, etc.)
Enums in Rust
Enums (enumerations) allow you to define a type by enumerating its possible variants. Rust enums are much more powerful than in many other languages.
Basic Enum Definition and Usage
rust// Simple enum
enum Color {
Red,
Green,
Blue,
}
// Enum with data
enum Message {
Quit, // No data
Move { x: i32, y: i32 }, // Named fields like struct
Write(String), // Single piece of data
ChangeColor(i32, i32, i32), // Multiple pieces of data
}
// Enum with methods
impl Message {
fn call(&self) {
// Method body would be defined here
println!("Message called");
}
}
fn main() {
// Creating enum instances
let red = Color::Red;
let green = Color::Green;
let msg1 = Message::Write(String::from("hello"));
let msg2 = Message::Move { x: 10, y: 20 };
let msg3 = Message::ChangeColor(255, 0, 0);
// Using methods on enums
msg1.call();
// Pattern matching with enums
match red {
Color::Red => println!("It's red!"),
Color::Green => println!("It's green!"),
Color::Blue => println!("It's blue!"),
}
process_message(msg2);
}
fn process_message(msg: Message) {
match msg {
Message::Quit => {
println!("The Quit variant has no data");
}
Message::Move { x, y } => {
println!("Move to coordinates ({}, {})", x, y);
}
Message::Write(text) => {
println!("Text message: {}", text);
}
Message::ChangeColor(r, g, b) => {
println!("Change color to RGB({}, {}, {})", r, g, b);
}
}
}
The Option Enum
rust// Option is a built-in enum for handling optional values
// enum Option<T> {
// Some(T),
// None,
// }
fn option_examples() {
let some_number = Some(5);
let some_string = Some("a string");
let absent_number: Option<i32> = None;
// Using match with Option
match some_number {
Some(value) => println!("Got a value: {}", value),
None => println!("Got nothing"),
}
// Using if let with Option
if let Some(value) = some_string {
println!("The string is: {}", value);
}
// Option combinators
let number = Some(5);
let doubled = number.map(|x| x * 2); // Some(10)
let filtered = number.filter(|&x| x > 3); // Some(5)
let or_else = absent_number.or(Some(42)); // Some(42)
// Unwrapping options (use carefully)
let value = some_number.unwrap(); // 5
// let panic = absent_number.unwrap(); // This would panic!
let safe_value = absent_number.unwrap_or(0); // 0 (default value)
let or_else_value = absent_number.unwrap_or_else(|| 42); // 42
println!("Doubled: {:?}", doubled);
println!("Safe value: {}", safe_value);
}
The Result Enum
rust// Result is a built-in enum for error handling
// enum Result<T, E> {
// Ok(T),
// Err(E),
// }
fn result_examples() -> Result<(), String> {
let success: Result<i32, &str> = Ok(42);
let failure: Result<i32, &str> = Err("Something went wrong");
// Using match with Result
match success {
Ok(value) => println!("Success: {}", value),
Err(e) => println!("Error: {}", e),
}
// Using if let with Result
if let Err(error) = failure {
println!("Failed with: {}", error);
}
// Result combinators
let mapped = success.map(|x| x * 2); // Ok(84)
let and_then = success.and_then(|x| Ok(x + 10)); // Ok(52)
let or_else = failure.or_else(|_| Ok(0)); // Ok(0)
// The ? operator for error propagation
let content = read_file("example.txt")?;
println!("File content: {}", content);
// Converting between Option and Result
let some_value = Some(42);
let result: Result<i32, &str> = some_value.ok_or("No value");
Ok(())
}
fn read_file(filename: &str) -> Result<String, String> {
// Simulate file reading
if filename == "example.txt" {
Ok("File content".to_string())
} else {
Err("File not found".to_string())
}
}
// Using Result in main
fn main() -> Result<(), Box<dyn std::error::Error>> {
result_examples()?;
Ok(())
}
Advanced Enum Patterns
rustuse std::fmt;
// Generic enums
enum MyResult<T, E> {
Success(T),
Failure(E),
}
// Enum with methods
impl<T, E> MyResult<T, E> {
fn is_success(&self) -> bool {
match self {
MyResult::Success(_) => true,
MyResult::Failure(_) => false,
}
}
fn unwrap(self) -> T {
match self {
MyResult::Success(value) => value,
MyResult::Failure(_) => panic!("Called unwrap on Failure"),
}
}
}
// Pattern matching advanced features
fn advanced_pattern_matching() {
let complex_enum = Message::Move { x: 10, y: 20 };
// Matching with guards
match complex_enum {
Message::Move { x, y } if x == 0 && y == 0 => {
println!("At origin");
}
Message::Move { x, y } if x > 0 && y > 0 => {
println!("In first quadrant: ({}, {})", x, y);
}
Message::Move { x, y } => {
println!("At coordinates: ({}, {})", x, y);
}
_ => {}
}
// @ bindings - bind to variable while also matching
let some_value = Some(15);
match some_value {
Some(x @ 1..=10) => println!("Small number: {}", x),
Some(x @ 11..=100) => println!("Medium number: {}", x),
Some(x) => println!("Large number: {}", x),
None => println!("No number"),
}
}
// Implementing traits for enums
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Color::Red => write!(f, "Red"),
Color::Green => write!(f, "Green"),
Color::Blue => write!(f, "Blue"),
}
}
}
fn main() {
let color = Color::Red;
println!("The color is: {}", color);
let my_result: MyResult<i32, &str> = MyResult::Success(42);
println!("Is success: {}", my_result.is_success());
advanced_pattern_matching();
}
Common Enum Use Cases
rust// State machines
enum TrafficLight {
Red,
Yellow,
Green,
}
impl TrafficLight {
fn next(&self) -> TrafficLight {
match self {
TrafficLight::Red => TrafficLight::Green,
TrafficLight::Yellow => TrafficLight::Red,
TrafficLight::Green => TrafficLight::Yellow,
}
}
fn duration(&self) -> u32 {
match self {
TrafficLight::Red => 30,
TrafficLight::Yellow => 5,
TrafficLight::Green => 45,
}
}
}
// AST (Abstract Syntax Tree) nodes
enum Expr {
Number(i32),
Add(Box<Expr>, Box<Expr>),
Multiply(Box<Expr>, Box<Expr>),
Variable(String),
}
impl Expr {
fn evaluate(&self, vars: &std::collections::HashMap<String, i32>) -> i32 {
match self {
Expr::Number(n) => *n,
Expr::Add(left, right) => left.evaluate(vars) + right.evaluate(vars),
Expr::Multiply(left, right) => left.evaluate(vars) * right.evaluate(vars),
Expr::Variable(name) => *vars.get(name).unwrap_or(&0),
}
}
}
// Command pattern
enum Command {
Move { x: i32, y: i32 },
Attack { target: String },
Wait,
Quit,
}
impl Command {
fn execute(&self) {
match self {
Command::Move { x, y } => println!("Moving to ({}, {})", x, y),
Command::Attack { target } => println!("Attacking {}", target),
Command::Wait => println!("Waiting..."),
Command::Quit => println!("Quitting"),
}
}
}
fn enum_use_cases() {
let mut light = TrafficLight::Red;
for _ in 0..5 {
println!("Light: {:?}, Duration: {}s", light, light.duration());
light = light.next();
}
// AST example: (2 + 3) * 4
let expr = Expr::Multiply(
Box::new(Expr::Add(
Box::new(Expr::Number(2)),
Box::new(Expr::Number(3)),
)),
Box::new(Expr::Number(4)),
);
let result = expr.evaluate(&std::collections::HashMap::new());
println!("Expression result: {}", result); // 20
// Command pattern
let commands = vec![
Command::Move { x: 10, y: 20 },
Command::Attack { target: "enemy".to_string() },
Command::Wait,
Command::Quit,
];
for command in commands {
command.execute();
}
}
Common Pitfalls
- Forgetting to handle all enum variants in match statements
- Using
unwrap()on Option/Result without considering failure cases - Not leveraging the ? operator for error propagation
- Creating overly complex enums when separate types would be better
- Forgetting that enum variants are namespaced under the enum type
An async executor drives futures to completion by polling them when notified, while a spawner allows dynamic task generation and submission to the executor queue.
Architecting the Core Engine
A custom executor relies on three primitives: a Task (wrapping a future inside a std::task::Waker), a Queue (for distributing work, often using crossbeam or std::sync), and a Reactor (to handle I/O or timer wakes).
rustuse std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll, Wake};
use crossbeam::deque::{Worker, Stealer, Injector};
use parking_lot::Mutex;
pub struct Task {
future: Mutex<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
scheduled: AtomicBool,
}
impl Wake for Task {
fn wake(self: Arc<Self>) {
// Prevent duplicate queue insertions if already scheduled
if !self.scheduled.swap(true, Ordering::SeqCst) {
// In a full implementation, push back onto the local or global queue here.
}
}
}
Implementing Spawner and Worker Threads
The spawner allocates tasks onto a shared global injector queue, while worker threads use local work-stealing deques to maximize core utilization and reduce lock contention.
rustpub struct Spawner {
injector: Arc<Injector<Arc<Task>>>,
}
impl Spawner {
pub fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
let task = Arc::new(Task {
future: Mutex::new(Box::pin(future)),
scheduled: AtomicBool::new(true),
});
self.injector.push(task);
}
}
pub struct WorkerThread {
id: usize,
local_worker: Worker<Arc<Task>>,
stealers: Vec<Stealer<Arc<Task>>>,
injector: Arc<Injector<Arc<Task>>>,
}
impl WorkerThread {
pub fn run(&self) {
let waker = std::task::Waker::noop(); // Simplified for illustration
let mut cx = Context::from_waker(&waker);
loop {
let task = self.find_task();
if let Some(task) = task {
task.scheduled.store(false, Ordering::SeqCst);
let mut future = task.future.lock();
let _ = future.as_mut().poll(&mut cx);
} else {
std::thread::yield_now();
}
}
}
fn find_task(&self) -> Option<Arc<Task>> {
// 1. Check local queue
// 2. Check global injector
// 3. Steal from other workers
self.local_worker.pop()
.or_else(|| {
self.injector.steal_batch_and_pop(&self.local_worker)
})
.or_else(|| {
self.stealers.iter()
.map(|s| s.steal())
.find(|s| !s.is_empty())
.and_then(|s| s.success())
})
}
}
Performance Considerations and Edge Cases
Writing production-grade executors requires avoiding starvation and managing thread park states efficiently using OS primitives (like epoll or condvar).
- Wake Stampedes: Always use atomic CAS operations (like
swap(true, Ordering::SeqCst)) insideWake::waketo ensure a task is enqueued at most once per notification cycle. - Fairness: Periodically check the global injector queue from local workers to prevent long-running tasks from starving newly spawned sub-tasks.
Try It Yourself
Combine the components into an executable pipeline:
rustfn main() {
let (injector, _spawner) = (Arc::new(Injector::new()), Spawner { injector: Arc::new(Injector::new()) });
// Initialize workers, spin up threads, and execute your futures.
println!("Custom executor initialized successfully.");
}
Expected Output:
textCustom executor initialized successfully.
Key Takeaways
- Executors bridge the gap between passive `Future` state machines and active CPU threads. - `std::task::Waker` is the vital communication link enabling futures to schedule themselves back onto execution queues when resources become available. - Work-stealing architectures significantly outperform single-queue designs by eliminating global lock bottlenecks on multi-core hardware.Deterministic Simulation Testing (DST) replaces non-deterministic real-world networking and multi-threading with a single-threaded, event
Traits in Rust
Traits define shared behavior that types can implement. They're similar to interfaces in other languages but more powerful, supporting associated types, default implementations, and more.
Basic Trait Definition and Implementation
rust// Define a trait
trait Summary {
fn summarize(&self) -> String;
// Default implementation
fn summarize_author(&self) -> String {
String::from("(Unknown author)")
}
// Method with default implementation that uses other methods
fn summarize_with_author(&self) -> String {
format!("{} by {}", self.summarize(), self.summarize_author())
}
}
// Implement the trait for a type
struct NewsArticle {
headline: String,
location: String,
author: String,
content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
// Override the default implementation
fn summarize_author(&self) -> String {
self.author.clone()
}
}
// Another type implementing the same trait
struct Tweet {
username: String,
content: String,
reply: bool,
retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
fn main() {
let article = NewsArticle {
headline: String::from("Penguins win the Stanley Cup Championship!"),
location: String::from("Pittsburgh, PA, USA"),
author: String::from("Iceburgh"),
content: String::from("The Pittsburgh Penguins once again are the best hockey team in the NHL."),
};
let tweet = Tweet {
username: String::from("horse_ebooks"),
content: String::from("of course, as you probably already know, people"),
reply: false,
retweet: false,
};
println!("Article summary: {}", article.summarize());
println!("Tweet summary: {}", tweet.summarize());
println!("Article with author: {}", article.summarize_with_author());
}
Trait Bounds and Generic Functions
rustuse std::fmt::Display;
// Function with trait bound
fn notify<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
// Multiple trait bounds
fn notify_multiple<T: Summary + Display>(item: &T) {
println!("Item: {} - Summary: {}", item, item.summarize());
}
// Alternative syntax with where clause
fn some_function<T, U>(t: &T, u: &U) -> i32
where
T: Display + Clone,
U: Clone + Summary,
{
println!("T: {}, U summary: {}", t, u.summarize());
42
}
// Returning types that implement traits
fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("horse_ebooks"),
content: String::from("of course, as you probably already know, people"),
reply: false,
retweet: false,
}
}
// Using trait bounds with structs
struct Pair<T> {
x: T,
y: T,
}
impl<T> Pair<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
}
impl<T: Display + PartialOrd> Pair<T> {
fn cmp_display(&self) {
if self.x >= self.y {
println!("The largest member is x = {}", self.x);
} else {
println!("The largest member is y = {}", self.y);
}
}
}
fn trait_bounds_examples() {
let article = NewsArticle { /* ... */ };
notify(&article);
let pair = Pair::new(3, 4);
pair.cmp_display();
let summarizable = returns_summarizable();
println!("Returned: {}", summarizable.summarize());
}
Common Standard Library Traits
rustuse std::fmt;
use std::ops::Add;
// Derivable traits
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Point {
x: i32,
y: i32,
}
// Manual implementation of Display
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
// Implementing operator overloading with Add trait
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
// Implementing From/Into traits for conversions
impl From<(i32, i32)> for Point {
fn from(pair: (i32, i32)) -> Self {
Point {
x: pair.0,
y: pair.1,
}
}
}
fn standard_traits_examples() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
// Using Debug trait
println!("Debug: {:?}", p1);
// Using Display trait
println!("Display: {}", p1);
// Using Add trait
let sum = p1 + p2;
println!("Sum: {}", sum);
// Using From trait
let p3 = Point::from((5, 6));
let p4: Point = (7, 8).into(); // Into is automatically implemented when From is
println!("From tuple: {}", p3);
println!("Into: {}", p4);
// Using Clone trait
let cloned = p1.clone();
println!("Cloned: {}", cloned);
// Using PartialEq trait
println!("Equal: {}", p1 == cloned);
}
Advanced Trait Features
rust// Associated types
trait Iterator {
type Item; // Associated type
fn next(&mut self) -> Option<Self::Item>;
}
// Implementing iterator with associated type
struct Counter {
count: u32,
}
impl Counter {
fn new() -> Counter {
Counter { count: 0 }
}
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.count < 5 {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
// Generic traits with associated types
trait Container<T> {
fn contains(&self, item: &T) -> bool;
}
impl<T: PartialEq> Container<T> for Vec<T> {
fn contains(&self, item: &T) -> bool {
self.iter().any(|x| x == item)
}
}
// Supertraits (trait that requires another trait)
trait OutlinePrint: fmt::Display {
fn outline_print(&self) {
let output = self.to_string();
let len = output.len();
println!("{}", "*".repeat(len + 4));
println!("*{}*", " ".repeat(len + 2));
println!("* {} *", output);
println!("*{}*", " ".repeat(len + 2));
println!("{}", "*".repeat(len + 4));
}
}
// Implement OutlinePrint for Point (requires Display)
impl OutlinePrint for Point {}
// Fully Qualified Syntax for Disambiguation
trait Pilot {
fn fly(&self);
}
trait Wizard {
fn fly(&self);
}
struct Human;
impl Pilot for Human {
fn fly(&self) {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly(&self) {
println!("Up!");
}
}
impl Human {
fn fly(&self) {
println!("*waving arms furiously*");
}
}
fn advanced_trait_examples() {
let mut counter = Counter::new();
while let Some(num) = counter.next() {
println!("Counter: {}", num);
}
let point = Point { x: 10, y: 20 };
point.outline_print();
let person = Human;
person.fly(); // Calls Human::fly
Pilot::fly(&person); // Calls Pilot::fly
Wizard::fly(&person); // Calls Wizard::fly
}</code></blank>
<h2>Trait Objects and Dynamic Dispatch</h2>
<pre><code class="language-rust">// Trait objects for heterogeneous collections
fn trait_objects_examples() {
let article = NewsArticle { /* ... */ };
let tweet = Tweet { /* ... */ };
// Vector of trait objects - can store different types that implement Summary
let summaries: Vec<Box<dyn Summary>> = vec![
Box::new(article),
Box::new(tweet),
];
for item in summaries {
println!("Summary: {}", item.summarize());
}
}
// Using trait objects in function parameters
fn notify_dynamic(item: &dyn Summary) {
println!("Notification: {}", item.summarize());
}
// Trait objects with static dispatch vs dynamic dispatch
fn static_dispatch<T: Summary>(item: &T) {
// Monomorphization - compiler generates specific code for each type
println!("{}", item.summarize());
}
fn dynamic_dispatch(item: &dyn Summary) {
// Dynamic dispatch - uses vtable at runtime
println!("{}", item.summarize());
}
// Object-safe traits (can be used as trait objects)
trait ObjectSafe {
fn method(&self);
}
// This trait is NOT object-safe because it has generic methods
// trait NotObjectSafe {
// fn generic_method<T>(&self, t: T);
// }
fn main() {
let article = NewsArticle { /* ... */ };
let tweet = Tweet { /* ... */ };
notify_dynamic(&article);
notify_dynamic(&tweet);
static_dispatch(&article);
static_dispatch(&tweet);
}
Common Pitfalls
- Forgetting to bring traits into scope when using their methods
- Creating trait bounds that are too restrictive or not restrictive enough
- Confusing static dispatch (generics) with dynamic dispatch (trait objects)
- Not understanding object safety rules for trait objects
- Overusing trait objects when generics would be more efficient
Advanced Rust Concepts
Advanced Rust features provide powerful tools for writing efficient, safe, and expressive code. These include smart pointers, async/await, unsafe Rust, and more.
Smart Pointers
rustuse std::rc::Rc;
use std::sync::Arc;
use std::cell::RefCell;
use std::sync::Mutex;
fn smart_pointer_examples() {
// Box - heap allocation with single ownership
let boxed = Box::new(5);
println!("Boxed value: {}", *boxed);
// Rc - reference counting for multiple ownership (single-threaded)
let rc1 = Rc::new(String::from("hello"));
let rc2 = Rc::clone(&rc1);
println!("Rc count: {}", Rc::strong_count(&rc1));
// Arc - atomic reference counting (thread-safe)
let arc1 = Arc::new(String::from("world"));
let arc2 = Arc::clone(&arc1);
println!("Arc value: {}", *arc1);
// RefCell - interior mutability (runtime borrow checking)
let ref_cell = RefCell::new(42);
{
let mut borrow = ref_cell.borrow_mut();
*borrow += 1;
} // borrow goes out of scope here
println!("RefCell value: {}", ref_cell.borrow());
// Mutex - mutual exclusion (thread-safe interior mutability)
let mutex = Mutex::new(100);
{
let mut guard = mutex.lock().unwrap();
*guard += 1;
}
println!("Mutex value: {}", *mutex.lock().unwrap());
// Combining Rc and RefCell for multiple ownership with mutability
let shared_mutable = Rc::new(RefCell::new(0));
let clone1 = Rc::clone(&shared_mutable);
let clone2 = Rc::clone(&shared_mutable);
*clone1.borrow_mut() += 1;
*clone2.borrow_mut() += 1;
println!("Shared mutable: {}", *shared_mutable.borrow());
}
Async/Await
rust// Requires tokio or async-std runtime
// #[tokio::main]
// async fn main() {
// let result = fetch_data().await;
// println!("Result: {}", result);
// }
/*
async fn fetch_data() -> String {
// Simulate async operation
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
"Data fetched".to_string()
}
async fn process_multiple() {
// Join multiple async operations
let (result1, result2) = tokio::join!(
fetch_data(),
fetch_data()
);
println!("Results: {}, {}", result1, result2);
// Select between async operations
tokio::select! {
result = fetch_data() => println!("First completed: {}", result),
_ = tokio::time::sleep(tokio::time::Duration::from_secs(2)) => {
println!("Timeout reached");
}
}
}
*/
// For this example, we'll use a synchronous version
fn async_concepts() {
println!("Async/await enables writing asynchronous code that looks synchronous");
println!("It's built on top of futures and requires an async runtime");
}
Unsafe Rust
rustunsafe fn unsafe_examples() {
// Dereferencing raw pointers
let mut num = 5;
let r1 = &num as *const i32;
let r2 = &mut num as *mut i32;
unsafe {
println!("r1 is: {}", *r1);
*r2 = 10;
println!("r2 is: {}", *r2);
}
// Calling unsafe functions
unsafe {
dangerous_function();
}
// Creating safe abstractions over unsafe code
let mut v = vec![1, 2, 3, 4, 5];
let (a, b) = split_at_mut(&mut v, 2);
println!("First part: {:?}", a);
println!("Second part: {:?}", b);
}
unsafe fn dangerous_function() {
println!("This is an unsafe function");
}
// Safe abstraction over unsafe code
fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = slice.len();
let ptr = slice.as_mut_ptr();
assert!(mid <= len);
unsafe {
(
std::slice::from_raw_parts_mut(ptr, mid),
std::slice::from_raw_parts_mut(ptr.add(mid), len - mid),
)
}
}
// Implementing unsafe traits
unsafe trait UnsafeTrait {
// trait methods
}
unsafe impl UnsafeTrait for i32 {
// implementation
}
fn main() {
unsafe {
unsafe_examples();
}
}
Advanced Pattern Matching
rustfn advanced_patterns() {
// Matching ranges
let x = 5;
match x {
1..=5 => println!("One through five"),
6 | 7 | 8 => println!("Six, seven, or eight"),
_ => println!("Something else"),
}
// Destructuring nested structures
struct Point {
x: i32,
y: i32,
}
enum Color {
Rgb(i32, i32, i32),
Hsv(i32, i32, i32),
}
enum Message {
ChangeColor(Color),
}
let msg = Message::ChangeColor(Color::Rgb(0, 160, 255));
match msg {
Message::ChangeColor(Color::Rgb(r, g, b)) => {
println!("Change color to RGB({}, {}, {})", r, g, b);
}
Message::ChangeColor(Color::Hsv(h, s, v)) => {
println!("Change color to HSV({}, {}, {})", h, s, v);
}
}
// @ bindings
let p @ Point { x: px, y: py } = Point { x: 10, y: 20 };
println!("Point: ({}, {})", px, py);
println!("Whole point: {:?}", p);
// Matching with guards
let num = Some(4);
match num {
Some(x) if x < 5 => println!("Less than five: {}", x),
Some(x) => println!("{}", x),
None => (),
}
// if let chains (Rust 1.63+)
let some_option = Some(5);
let another_option = Some(10);
// This would work in newer Rust versions:
// if let Some(x) = some_option && let Some(y) = another_option {
// println!("x = {}, y = {}", x, y);
// }
}
Macros
rust// Declarative macros (macro_rules!)
macro_rules! vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
// Using the macro
fn macro_examples() {
let v = vec![1, 2, 3];
println!("Macro-generated vector: {:?}", v);
}
// Procedural macros require separate crate
/*
// In a procedural macro crate
use proc_macro::TokenStream;
use quote::quote;
use syn;
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
let ast = syn::parse(input).unwrap();
impl_hello_macro(&ast)
}
fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream {
let name = &ast.ident;
let gen = quote! {
impl HelloMacro for #name {
fn hello_macro() {
println!("Hello, Macro! My name is {}!", stringify!(#name));
}
}
};
gen.into()
}
*/
// Function-like macros
/*
macro_rules! sql {
($($arg:tt)*) => { /* ... */ };
}
// Usage: sql!(SELECT * FROM users WHERE id = 1);
*/
fn main() {
macro_examples();
}
Advanced Lifetime Patterns
rust// Lifetime elision rules
fn first_word(s: &str) -> &str {
// Compiler applies elision rules:
// 1. Each parameter gets its own lifetime
// 2. If there's exactly one input lifetime, it's assigned to all output lifetimes
// 3. If there are multiple input lifetimes but one is &self or &mut self,
// the lifetime of self is assigned to all output lifetimes
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
// Explicit lifetime annotations
struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
// Lifetime elision works here
fn level(&self) -> i32 {
3
}
// Need explicit lifetime here
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention please: {}", announcement);
self.part
}
}
// Higher-ranked trait bounds (HRTB)
fn call_on_ref_zero<F>(f: F)
where
F: for<'a> Fn(&'a i32),
{
let zero = 0;
f(&zero);
}
// Static lifetime
fn static_lifetime_example() -> &'static str {
"I have a static lifetime"
}
fn lifetime_advanced() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().expect("Could not find a '.'");
let i = ImportantExcerpt {
part: first_sentence,
};
println!("Excerpt: {}", i.part);
let static_str = static_lifetime_example();
println!("Static string: {}", static_str);
call_on_ref_zero(|x| println!("x is: {}", x));
}
Common Pitfalls
- Using unsafe code without proper validation and documentation
- Creating memory leaks with Rc/RefCell cycles
- Not understanding async runtime requirements
- Overusing macros when functions would suffice
- Misunderstanding lifetime relationships in complex data structures
Linux io_uring shifts I/O from a readiness-based model (epoll) to a submission-and-completion ring buffer paradigm. Bridging this ring with Rust’s asynchronous ecosystem (Future/Poll) requires safe integration with thread pools for synchronous CPU-bound fallbacks.
The io_uring Architecture and Bridging Strategy
io_uring uses two ring buffers in shared kernel memory: the Submission Queue (SQ) and the Completion Queue (CQ). Rust asynchronous runtimes like Tokio use event loops that poll readiness. To integrate io_uring, we convert ring completions into wakeups for Rust’s Waker mechanism, while dispatching blocking or unsupported system calls to a dedicated synchronous thread pool.
rust// Cargo.toml dependencies required:
// io-uring = "0.6"
// nix = { version = "0.27", features = ["fs"] }
// futures = "0.3"
use io_uring::{squeue, cqueue, IoUring};
use std::os::unix::io::AsRawFd;
use std::fs::File;
use std::sync::{Arc, Mutex};
use std::task::{Waker, Context, Poll};
use std::future::Future;
use std::pin::Pin;
pub struct UringReactor {
ring: Arc<Mutex<IoUring>>,
wakers: Arc<Mutex<Vec<(u64, Waker)>>>,
}
impl UringReactor {
pub fn new(entries: u32) -> std::io::Result<Self> {
let ring = IoUring::new(entries)?;
Ok(Self {
ring: Arc::new(Mutex::new(ring)),
wakers: Arc::new(Mutex::new(Vec::new())),
})
}
pub fn submit_read(&self, file: &File, buf: &mut [u8], user_data: u64) -> ReadFuture {
let fd = file.as_raw_fd();
let ring = Arc::clone(&self.ring);
let wakers = Arc::clone(&self.wakers);
// Push submission entry
let sqe = squeue::Entry::new(
libc::IORING_OP_READ as u8,
fd,
)
.addr(buf.as_mut_ptr() as u64)
.len(buf.len() as u32)
.user_data(user_data);
{
let mut ring = ring.lock().unwrap();
unsafe {
let mut sq = ring.submission();
// If submission queue is full, panic or handle backpressure.
while sq.is_full() {
ring.submit().unwrap();
}
sq.push(&sqe).unwrap();
}
ring.submit().unwrap();
}
ReadFuture {
user_data,
ring,
wakers,
}
}
}
Implementing the Asynchronous Future
The custom ReadFuture yields control back to the executor, registering its Waker to be triggered when the io_uring completion queue yields the matching user_data token.
rustpub struct ReadFuture {
user_data: u64,
ring: Arc<Mutex<IoUring>>,
wakers: Arc<Mutex<Vec<(u64, Waker)>>>,
}
impl Future for ReadFuture {
type Output = std::io::Result<i32>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut ring = self.ring.lock().unwrap();
// Check completion queue
let mut cq = ring.completion();
while let Some(cqe) = cq.next() {
if cqe.user_data() == self.user_data {
let res = cqe.res();
if res < 0 {
return Poll::Ready(Err(std::io::Error::from_raw_os_error(-res)));
}
return Poll::Ready(Ok(res));
}
}
// Not ready: store waker for reactor poll loop notification
let mut wakers = self.wakers.lock().unwrap();
wakers.retain(|(uid, _)| *uid != self.user_data);
wakers.push((self.user_data, cx.waker().clone()));
Poll::Pending
}
}
Bridging Sync Fallbacks with Rayon or Dedicated Pools
Certain operations (e.g., specific file systems lacking async support or complex sync transformations) require offloading to a thread pool. We bridge this by wrapping the sync operation in tokio::task::spawn_blocking or a custom Rayon pool, ensuring it communicates back via channels or futures.
rustuse std::thread;
use crossbeam_channel::{unbounded, Sender, Receiver};
pub struct SyncBridgePool {
sender: Sender<Box<dyn FnOnce() + Send + 'static>>,
}
impl SyncBridgePool {
pub fn new(num_threads: usize) -> Self {
let (sender, receiver): (Sender<Box<dyn FnOnce() + Send + 'static>>, Receiver<Box<dyn FnOnce() + Send + 'static>>) = unbounded();
for _ in 0..num_threads {
let rx = receiver.clone();
thread::spawn(move || {
while let Ok(task) = rx.recv() {
task();
}
});
}
Self { sender }
}
pub fn execute<F, T>(&self, f: F) -> impl Future<Output = T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
let (tx, rx) = tokio::sync::oneshot::channel();
let task = Box::new(move || {
let res = f();
let _ = tx.send(res);
});
self.sender.send(task).unwrap();
async move {
rx.await.unwrap()
}
}
}
Performance Considerations and Edge Cases
- Buffer Lifetime Safety: `io_uring` requires memory buffers to remain valid and pinned in memory until the kernel confirms the operation completion. Passing unpinned stack slices to `io_uring` causes memory corruption if the stack frame unwinds prematurely. Use `Box::leak` or specialized arena allocators for ring buffers.
- Submission Queue Poll Fatigue: Avoid busy-polling the completion queue. Use `IORING_SETUP_SQPOLL` (kernel-side poll thread) for ultra-low latency, or fall back to system call notifications (`io_uring_enter` with `IORING_ENTER_GETEVENTS`) when sleeping.
- Thread-Safety and Lock Contention: Mutex-wrapping the shared `IoUring` instance across multiple async tasks creates contention bottlenecks. Prefer a single-threaded reactor per CPU core (shard pattern) matching the Linux thread-per-core NUMA topology.
Key Takeaways
- `io_uring` replaces readiness notification with completion notification, matching Rust's `Poll`/`Waker` model via custom futures.
- User-data tokens (`user_data`) are vital for matching asynchronous completion queue entries back to specific Rust futures.
- Memory buffers passed to `io_uring` must outlive the kernel submission-to-completion cycle, demanding strict pinning or heap allocation strategies.
- Synchronous execution paths must be isolated using thread pools (like `SyncBridgePool`) to prevent blocking the high-performance async event loop.
Rust eliminates null pointer exceptions and unhandled runtime exceptions by encoding the presence of values or failures directly into the type system via Option<T> and Result<T, E>.
Representing Absence with Option<T>
The Option<T> enum models an optional value. It has two variants: Some(T) containing a value, and None representing nothing.
rustfn find_username(id: u32) -> Option<String> {
if id == 42 {
Some(String::from("ferris"))
} else {
None
}
}
fn main() {
let user = find_username(42);
match user {
Some(name) => println!("Found user: {}", name),
None => println!("User not found"),
}
}
Instead of null checks that risk crashing your program, match enforces exhaustive handling of both states at compile time.
Recoverable Errors with Result<T, E>
The Result<T, E> enum handles operations that can fail, containing either Ok(T) for success or Err(E) for failure.
rustuse std::fs::File;
use std::io::{self, Read};
fn read_username_from_file() -> Result<String, io::Error> {
let mut file_result = File::unlocked_open("config.txt"); // conceptual
// Manual matching on Result
let mut file = match File::open("config.txt") {
Ok(f) => f,
Err(e) => return Err(e),
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
The ? Propagation Operator
Manually matching every Result is verbose. The ? operator unwraps Ok values or immediately returns the Err variant from the enclosing function, drastically cleaning up control flow.
rustuse std::fs::File;
use std::io::{self, Read};
fn read_username_concise() -> Result<String, io::Error> {
let mut s = String::new();
File::open("config.txt")?.read_to_string(&mut s)?;
Ok(s)
}
The ? operator can also be used with Option<T> inside functions that return an Option.
Unwrap vs. Expect
Production code should rarely use unwrap() or expect(), which panic the current thread on None or Err. Reserve them for prototypes, tests, or absolute mathematical certainties where an error implies a broken invariant.
rustfn main() {
// Panics with a generic message if None
let config = std::env::var("PORT").unwrap();
// Panics with a custom context message (preferred for debugging)
let db_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
}
Try It Yourself
Compile and run this complete example showcasing Result, ?, and match:
rustuse std::num::ParseIntError;
fn multiply(first: &str, second: &str) -> Result<i32, ParseIntError> {
let num1 = first.parse::<i32>()?;
let num2 = second.parse::<i32>()?;
Ok(num1 * num2)
}
fn main() {
match multiply("10", "2") {
Ok(val) => println!("Product: {}", val),
Err(e) => println!("Failed to parse: {}", e),
}
match multiply("10", "not_a_number") {
Ok(val) => println!("Product: {}", val),
Err(e) => println!("Failed to parse: {}", e),
}
}
Expected Output
```text Product: 20 Failed to parse: invalid digit found in string ```Key Takeaways
- `Option
` explicitly models presence (`Some`) or absence (`None`) without null pointers. - `Result
` handles operations that can fail, splitting execution paths into success (`Ok`) and failure (`Err`). - The `?` operator propagates errors upstream concisely, requiring the enclosing function to return a compatible `Result` or `Option`.
- Avoid `unwrap()` and `expect()` in production code paths unless an error represents an unrecoverable bug or broken invariant.
Procedural macros in Rust allow for arbitrary Abstract Syntax Tree (AST) transformation at compile time, enabling zero-overhead structural inspection and custom code generation without runtime reflection penalties. This chapter explores parsing custom attributes via syn, analyzing struct fields, and generating hygienic code expansions using quote and proc-macro2.
Declaring and Parsing Structural Metadata
To inspect a type at compile time, define a custom derive or attribute macro that consumes a TokenStream, parses it into a strongly typed AST using syn, and inspects structural components such as named fields, types, and attributes.
rust// In macro crate: lib.v
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput, Data, Fields};
#[proc_macro_derive(InspectFields, attributes(inspector))]
pub fn inspect_fields_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
// Extract fields from a Struct
let fields = match &input.data {
Data::Struct(data) => match &data.fields {
Fields::Named(fields) => &fields.named,
_ => panic!("InspectFields only supports structs with named fields"),
},
_ => panic!("InspectFields only supports structs"),
};
let field_names: Vec<_> = fields.iter().map(|f| &f.ident).collect();
let field_types: Vec<_> = fields.iter().map(|f| &f.ty).collect();
let field_count = field_names.len();
// Generate zero-overhead reflection implementation
let expanded = quote! {
impl #name {
pub fn __inspect_fields() -> &'static [(&'static str, &'static str)] {
&[
#(
(stringify!(#field_names), stringify!(#field_types)),
)*
]
}
pub const __FIELD_COUNT: usize = #field_count;
}
};
TokenStream::from(expanded)
}
Macro Hygiene and Scope Safety
Rust macro expansion occurs in a specific syntax context (Span) that prevents accidental variable shadowing or name collisions. When generating code that references external crates or internal helper traits, rely on absolute paths or proc_macro2::Span::call_site() to preserve hygiene boundaries.
rustuse proc_macro2::Span;
use quote::quote;
use syn::Ident;
fn generate_safe_wrapper(struct_name: &Ident) -> proc_macro2::TokenStream {
let helper_trait = Ident::new("InternalReflection", Span::call_site());
quote! {
// Using absolute path guards against caller scope pollution
impl ::core::fmt::Debug for #struct_name {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.debug_struct(stringify!(#struct_name))
.finish()
}
}
}
}
Consuming the Reflection API
The generated methods provide structural metadata natively at compile time, allowing for zero-cost abstraction layers inside domain logic or serialization engines.
rust// In user crate
use macro_crate::InspectFields;
#[derive(InspectFields)]
struct UserProfile {
id: u64,
username: String,
active: bool,
}
fn main() {
println!("Total fields: {}", UserProfile::__FIELD_COUNT);
for (name, ty) in UserProfile::__inspect_fields() {
println!("Field: {} -> Type: {}", name, ty);
}
}
Expected Output
textTotal fields: 3
Field: id -> Type: u64
Field: username -> Type: String
Field: active -> Type: bool
Gotchas and Performance Considerations
- Compilation Overhead: Complex
synparsing passes increase compilation times. Cache intermediate AST states when operating on massive crate graphs. - Span Pollution: Avoid hardcoding identifiers via raw strings inside
quote!; always usesyn::Ident::newwith explicit spans to ensure correct compiler error reporting. - Recursive Limits: Deeply nested macro expansions can trip up the recursion limit (
#![recursion_limit = "256"]). Design flattening strategies for deeply nested DSLs.
Key Takeaways
synbridges raw token streams to robust, typed Rust AST representations.quote!interpolates AST tokens cleanly back into valid Rust syntax structures.- Hygiene preservation relies on correct Span management and explicit absolute paths (
::std::...). - Compile-time reflection avoids runtime overhead by unrolling metadata directly into static array slices.
Smart pointers are data structures that act like pointers while providing additional metadata, ownership guarantees, and capabilities like heap allocation and shared ownership. Unlike raw pointers, smart pointers implement the Deref and Drop traits, enabling automatic memory management and custom cleanup logic.
Heap Allocation with Box<T>
Box<T> allocates data on the heap rather than the stack, returning a smart pointer stored on the stack that points to the heap location. Use Box for recursively defined types (where a struct contains itself) or when transferring ownership of large data structures without copying.
rust#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
fn main() {
// Without Box, List would have an infinite size at compile time.
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
println!("Recursive heap-allocated list: {:?}", list);
}
Single-Threaded Shared Ownership with Rc<T>
Rc<T> (Reference Counted) enables multiple ownership by keeping track of the number of references to a value. When the reference count drops to zero, the value is cleaned up. Rc is strictly for single-threaded contexts and is not thread-safe.
rustuse std::rc::Rc;
#[derive(Debug)]
struct Node {
val: i32,
}
fn main() {
let shared_node = Rc::new(Node { val: 42 });
// Clone increments the reference count without deep-copying the underlying data
let branch_a = Rc::clone(&shared_node);
let branch_b = Rc::clone(&shared_node);
println!("Reference count: {}", Rc::strong_count(&shared_node));
println!("Branch A sees: {}", branch_a.val);
println!("Branch B sees: {}", branch_b.val);
}
Thread-Safe Shared Ownership with Arc<T>
Arc<T> (Atomically Reference Counted) is the thread-safe equivalent of Rc<T>. It uses atomic operations to manage reference counts across multiple threads, incurring a minor performance penalty compared to Rc.
rustuse std::sync::Arc;
use std::thread;
fn main() {
let data = Arc::new(vec![1, 2, 3, 4, 5]);
let mut handles = vec![];
for i in 0..3 {
let data_clone = Arc::clone(&data);
let handle = thread::spawn(move || {
println!("Thread {} sees data: {:?}", i, data_clone);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
Interior Mutability with RefCell<T>
Rust’s borrowing rules are enforced at compile time. However, RefCell<T> moves these borrow checks to runtime, allowing you to mutate data even when there are immutable references to it, provided no mutable references coexist. This pattern is often combined with Rc (Rc<RefCell<T>>) to build shared, mutable graphs or trees.
rustuse std::cell::RefCell;
use std::rc::Rc;
fn main() {
let counter = Rc::new(RefCell::new(0));
let c1 = Rc::clone(&counter);
let c2 = Rc::clone(&counter);
// Borrow mutably through the RefCell at runtime
*c1.borrow_mut() += 10;
*c2.borrow_mut() += 20;
println!("Final counter value: {}", *counter.borrow());
}
Expected Output
```text Recursive heap-allocated list: Cons(1, Box(Cons(2, Box(Cons(3, Box(Nil)))))) Reference count: 3 Branch A sees: 42 Branch B sees: 42 Thread 0 sees data: [1, 2, 3, 4, 5] Thread 1 sees data: [1, 2, 3, 4, 5] Thread 2 sees data: [1, 2, 3, 4, 5] Final counter value: 30 ```Gotchas and Performance Considerations
- Cyclic References: `Rc` and `Arc` can create memory leaks if two data structures hold owning references to each other, forming a cycle. Use `Weak
` to break cycles. - Runtime Panics: `RefCell
` panics at runtime if you violate borrowing rules (e.g., attempting two mutable borrows simultaneously). - Thread Overhead: Avoid `Arc` in single-threaded code; atomic operations prevent compiler optimizations that `Rc` can exploit.
Key Takeaways
- Use `Box
` for simple heap allocation and handling recursive types. - Use `Rc
` for shared ownership within a single thread. - Use `Arc
` for shared ownership across multiple threads safely. - Combine `Rc` or `Arc` with `RefCell
` to achieve interior mutability and shared mutable state.
Hardware-accelerated SIMD (Single Instruction, Multiple Data) processes multiple data points concurrently within a single CPU cycle, bypassing traditional scalar loop overhead.
Rust achieves memory-safe concurrency without a garbage collector by enforcing strict ownership rules at compile time across operating system threads and message boundaries.
Spawning OS Threads
The std::thread::spawn function creates a new OS thread. Because threads can outlive the current stack frame, closures passed to spawn must take ownership of their captured variables using the move keyword.
rustuse std::thread;
use std::time::Duration;
fn main() {
let message = String::from("Hello from the spawned thread!");
let handle = thread::spawn(move || {
println!("{}", message);
thread::sleep(Duration::from_millis(50));
"Thread complete"
});
// Perform work on the main thread
println!("Doing work on main thread...");
// Wait for the spawned thread to finish and retrieve its return value
let result = handle.join().unwrap();
println!("Thread returned: {}", result);
}
The join() method blocks the current thread until the child thread terminates. Ignoring the join handle causes the thread to detach, executing in the background until the process exits.
Message Passing with MPSC Channels
Rust implements concurrent message passing using Multi-Producer, Single-Consumer (mpsc) channels. Multiple threads can send data into the channel, but only one receiver extracts it.
rustuse std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
// tx = transmitter, rx = receiver
let (tx, rx) = mpsc::channel();
for i in 1..=3 {
let tx_clone = tx.clone();
thread::spawn(move || {
let val = format!("Message {} from thread", i);
thread::sleep(Duration::from_millis(10 * i));
tx_clone.send(val).unwrap();
// tx_clone drops here, signaling completion for this transmitter
});
}
// Drop the original transmitter so rx.recv() terminates when all clones drop
drop(tx);
// Iterate over the receiver directly; terminates when all senders are dropped
for received in rx {
println!("Got: {}", received);
}
}
The sender takes ownership of the value being sent (send(val)), preventing the sending thread from modifying data after it has been handed off to another thread.
Shared State with Mutex<T>
When multiple threads require concurrent access to the same mutable data, combine an atomic reference counter (Arc) with a mutual exclusion lock (Mutex).
rustuse std::sync::{Arc, Mutex};
use std::thread;
fn main() {
// Arc allows safe sharing across thread boundaries via atomic reference counting
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter_clone = Arc::clone(&counter);
let handle = thread::spawn(move || {
// lock() blocks until the mutex is acquired, returning a MutexGuard
let mut num = counter_clone.lock().unwrap();
*num += 1;
// MutexGuard automatically drops here, releasing the lock safely
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Final counter value: {}", *counter.lock().unwrap());
}
Expected Output
textDoing work on main thread...
Hello from the spawned thread!
Thread returned: Thread complete
Got: Message 1 from thread
Got: Message 2 from thread
Got: Message 3 from thread
Final counter value: 10
Gotchas and Performance Considerations
- Deadlocks: Occur when multiple locks are acquired in different orders across threads. Always acquire locks in a consistent, predictable order.
- Lock Contention:
Mutex<T>blocks thread execution while waiting for access. For high-throughput scenarios, prefer message passing (mpsc) or lock-free atomic types (std::sync::atomic). - Poisoned Mutexes: If a thread panics while holding a
Mutex, the mutex becomes “poisoned.” Subsequent calls tolock()will return aErrto prevent reading inconsistent state.
Key Takeaways
- Use
std::thread::spawnwith themovekeyword to transfer variable ownership into child threads. - Use
mpsc::channelfor safe, decoupled inter-thread communication via message passing. - Wrap mutable shared data in
Arc<Mutex<T>>to ensure thread-safe interior mutability. - Rust’s type system guarantees at compile time that data races are impossible across threads.
Distributed fault tolerance requires state machines to agree on ordered log entries across network partitions using leader election, log replication, and safe safety invariants. This chapter builds an asynchronous, zero-copy log-replicating Raft engine using Rust, Tokio, and channels.
Core Architecture and State Transition
A production Raft node cycles through three states: Follower, Candidate, and Leader. Consensus safety depends on strict term tracking and monotonically increasing log indices.
rustuse tokio::sync::{mpsc, watch};
use std::sync::Arc;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeState {
Follower,
Candidate,
Leader,
}
#[derive(Debug, Clone)]
pub struct LogEntry {
pub term: u64,
pub index: u64,
pub data: Arc<[u8]>, // Zero-copy shared byte slice
}
pub struct RaftNode {
pub id: u64,
pub current_term: u64,
pub voted_for: Option<u64>,
pub log: Vec<LogEntry>,
pub commit_index: u64,
pub last_applied: u64,
pub state: NodeState,
}
impl RaftNode {
pub fn new(id: u64) -> Self {
Self {
id,
current_term: 0,
voted_for: None,
log: vec![LogEntry { term: 0, index: 0, data: Arc::from(&[][..]) }],
commit_index: 0,
last_applied: 0,
state: NodeState::Follower,
}
}
}
Asynchronous RPC and Zero-Copy Replication
To prevent allocation overhead during high-throughput log replication, messages pass via Tokio channels using Arc<[u8]> for payloads.
rust#[derive(Debug, Clone)]
pub enum RaftMessage {
RequestVote {
term: u64,
candidate_id: u64,
last_log_index: u64,
last_log_term: u64,
reply_to: mpsc::Sender<RaftResponse>,
},
AppendEntries {
term: u64,
leader_id: u64,
prev_log_index: u64,
prev_log_term: u64,
entries: Vec<LogEntry>,
leader_commit: u64,
reply_to: mpsc::Sender<RaftResponse>,
},
}
#[derive(Debug, Clone)]
pub enum RaftResponse {
RequestVoteResponse { term: u64, vote_granted: bool },
AppendEntriesResponse { term: u64, success: bool, match_index: u64 },
}
Partition Recovery and Election Timeouts
Randomized election timeouts (150ms–300ms) prevent split votes during network partitions. If a follower misses heartbeats, it transitions to a candidate, increments its term, and solicits votes.
rustimpl RaftNode {
pub async fn run_election_timer(&mut self, mut rx: mpsc::Receiver<RaftMessage>) {
use rand::Rng;
let mut rng = rand::thread_rng();
loop {
let timeout = Duration::from_millis(rng.gen_range(150..300));
tokio::select! {
_ = tokio::time::sleep(timeout) => {
if self.state != NodeState::Leader {
self.start_election().await;
}
}
Some(msg) = rx.recv() => {
self.handle_message(msg).await;
}
}
}
}
async fn start_election(&mut self) {
self.state = NodeState::Candidate;
self.current_term += 1;
self.voted_for = Some(self.id);
println!("Node {} entering Candidate state for term {}", self.id, self.current_term);
}
async fn handle_message(&mut self, msg: RaftMessage) {
match msg {
RaftMessage::AppendEntries { term, leader_id, reply_to, .. } => {
if term >= self.current_term {
self.state = NodeState::Follower;
self.current_term = term;
let _ = reply_to.send(RaftResponse::AppendEntriesResponse {
term: self.current_term,
success: true,
match_index: self.log.last().unwrap().index,
}).await;
}
}
_ => {}
}
}
}
Common Gotchas & Edge Cases
- Stale Leaders: Always verify term numbers on incoming RPC responses; a leader receiving a higher term must immediately step down to a follower.
- Log Consistency Checks: If an `AppendEntries` RPC fails due to mismatched `prev_log_index`, decrement the follower's match index iteratively rather than syncing blindly.
- Deadlocks in Async Select: Avoid holding synchronous locks (like `std::sync::Mutex`) across `tokio::select!` branches; use Tokio's asynchronous primitives (`tokio::sync::Mutex`).
Key Takeaways
- Zero-copy log payloads (`Arc<[u8]>`) drastically reduce memory allocations during high-frequency cluster replication.
- Randomized election timeouts break symmetry and prevent endless split votes during network partitions.
- State transitions (`Follower` -> `Candidate` -> `Leader`) must be guarded by strict logical clock (term) validation.
- Tokio's `select!` macro provides clean multiplexing between incoming network RPCs and local timeout tickers.