Skip to content

CatCode79/tips_from_rust_bytes_newsletter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 

Repository files navigation

Tips from the Rust Bytes Newsletter

Index of Tips


This guarantees the layout is exactly the same as the inner type, lets you do transmute-free conversions, and is the idiomatic way to wrap raw handles/pointers.

#[repr(transparent)]
pub struct Handle(NonZeroU32);

#[repr(transparent)]
pub struct Opaque(*mut c_void);

You can play around with the code on Rust Playground.


ManuallyDrop + ptr::write for move out without drop patterns

Want to move a value out of a struct without dropping the rest?

Combine ManuallyDrop with ptr::read/write:

let mut thing = ManuallyDrop::new(my_struct);
let field = ptr::read(&thing.field); // moves out
// now you can drop the rest manually or forget

I use this constantly when implementing arenas, intrusive linked lists, or custom Box-like types.


std::ptr::addr_of! and addr_of_mut!: your new best friends for field projection

When you need a raw pointer to a field without going through a reference to avoid stacked borrows or temporary references, use:

let ptr = std::ptr::addr_of!((*some_ptr).field);
let mut_ptr = std::ptr::addr_of_mut!((*some_ptr).field);

This is UB-free in cases where &(*some_ptr).field would create illegal intermediate references (very common in unsafe FFI, kernel, or intrusive data structures).

Check out and run the example on Rust Playground.


#[track_caller] + std::panic::Location for god-tier debugging in libraries

Want your library’s error messages/panics/logs to point to the user’s code, not your internal helper?

#[track_caller]
pub fn my_library_function() {
    let location = std::panic::Location::caller();
    println!("called from {}:{}", location.file(), location.line());
}

I put this on every public-facing helper that could fail. Makes debugging 10× nicer for downstream users.

Check out and run the example on Rust Playground.


Embed static data with include_str!

Need to bundle static text with your program? Use include_str! to read a file at compile time and embed it directly into the binary:

fn main() {
    const TEXT: &str = include_str!("static-data.txt");
    let program = include_str!("main.rs");
}

The file is read at build time, not at runtime. If you need to read a file while the program is running, use fs::read_to_string instead.

A particularly neat trick is to reuse your README.md file as crate documentation:

#![doc = include_str!("../README.md")]

Now you only have to write your documentation once. The same file powers your GitHub page, your cargo doc output, and your page on crates.io, including examples and doctests.


Prefer From/TryFrom over as

Using as for numeric conversions can silently truncate values when the destination type is smaller. That’s rarely what you want.

For infallible conversions, use From:

let output = u64::from(input);

If this compiles, the conversion is guaranteed to be sound. Rust won’t let you accidentally convert a larger type into a smaller one.

For conversions that may or may not succeed depending on the value, use TryFrom:

if let Ok(output) = u8::try_from(input) {}

TryFrom returns a Result:Ok if the value fits, Err if it doesn’t.

You can run the code on Rust Playground.


matches! for Fast, Readable Pattern Checks

matches! is a macro that evaluates to true if a value fits a given pattern. It’s essentially a compact, expression-based alternative to if let or a full match when you only care about a boolean result.

Instead of writing

enum State {
    Ready,
    Busy(u32)
}

fn is_busy(s: &State) -> bool {
    if let State::Busy(_) = s {
        true
    } else {
        false
    }
}

You write

enum State {
    Ready,
    Busy(u32)
}

fn is_busy_with_matches(s: &State) -> bool {
    matches!(s, State::Busy(_))
}

It also supports guards for additional constraints.

fn is_heavily_busy(s: &State) -> bool {
    matches!(s, State::Busy(n) if n > 10)
}

You can run the code on Rust Playground.


Const generics for Type-Safe Matrix Operations

Const Generics enable parameterizing types with compile-time constants, such as array or matrix dimensions.

It’s ideal for performance-critical applications like numerics, embedded systems, or games, allowing fixed-size matrices to be allocated without the overhead associated with dynamic vectors.

#[derive(Clone, Copy)]
struct Matrix<const ROWS: usize, const COLS: usize> {
    data: [[f32; COLS]; ROWS],
}

impl<const ROWS: usize, const COLS: usize> Matrix<ROWS, COLS> {
    fn zero() -> Self {
        Matrix {
            data: [[0.0; COLS]; ROWS],
        }
    }
}

fn add<const ROWS: usize, const COLS: usize>(
    a: &Matrix<ROWS, COLS>,
    b: &Matrix<ROWS, COLS>,
) -> Matrix<ROWS, COLS> {
    let mut result = Matrix::zero();
    for i in 0..ROWS {
        for j in 0..COLS {
            result.data[i][j] = a.data[i][j] + b.data[i][j];
        }
    }
    result
}

fn main() {
    let mat1: Matrix<2, 2> = Matrix {
        data: [[1.0, 2.0], [3.0, 4.0]],
    };
    let mat2: Matrix<2, 2> = Matrix {
        data: [[5.0, 6.0], [7.0, 8.0]],
    };

    let sum = add(&mat1, &mat2);

    println!("Matrix 1: {:?}", mat1.data);
    println!("Matrix 2: {:?}", mat2.data);
    println!("Sum: {:?}", sum.data);

    // Access an element
    println!("Element at [1][1] in sum: {}", sum.data[1][1]); // 12.0
}

You can run the code on Rust Playground.


bool::then: Lazy Option Creation

bool::then can be used as an alternative to if-else when building Option conditionally.

It’s also lazy, so the closure only runs if true, skipping all work (allocations, I/O, heavy calculations) when false.

Instead of writing

fn main() {
    let verbose_a = true;

    let log_prefix_a: Option<String> = if verbose_a {
        Some("[DEBUG]".to_string())
    } else {
        None
    };

    println!("if-else result: {:?}", log_prefix_a); // Some("[DEBUG]")

You write

    let verbose_b = true;

    let log_prefix_b: Option<String> = verbose_b.then(|| {
        "[DEBUG]".to_string() // Closure runs ONLY if true – zero cost otherwise
    });

    println!(".then result:  {:?}", log_prefix_b); // Some("[DEBUG]")
}

You can play around with the code on Rust Playground.

About

Tips From Rust Bytes

Resources

License

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors