rust

rust
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {

Unit tests with #[test] and assert macros

rust testing
by Marcus Chen 1 tab
rust
use std::fmt::Display;

fn make_adder(x: i32) -> impl Fn(i32) -> i32 {
    move |y| x + y
}

impl Trait for opaque return types

rust traits
by Marcus Chen 1 tab
rust
enum List {
    Cons(i32, Box<List>),
    Nil,
}

use List::{Cons, Nil};

Box<T> for heap allocation and recursive types

rust smart-pointers heap
by Marcus Chen 1 tab
rust
use once_cell::sync::Lazy;
use regex::Regex;

static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^[^ @]+@[^ @]+.[^ @]+$").unwrap()
});

once_cell for lazy static initialization

rust initialization patterns
by Marcus Chen 1 tab
rust
use parking_lot::Mutex;
use std::sync::Arc;
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));

Parking_lot for faster synchronization primitives

rust concurrency performance
by Marcus Chen 1 tab
rust
use std::pin::Pin;
use std::future::Future;

async fn example() {
    println!("Example future");
}

Pin and Unpin for safe self-referential async futures

rust async pin
by Marcus Chen 1 tab
rust
fn take_ownership(s: String) {
    println!("Took ownership: {}", s);
} // s is dropped here

fn main() {
    let message = String::from("hello");

Ownership transfer prevents double-free and use-after-free

rust ownership memory-safety
by Marcus Chen 1 tab
rust
use std::process::Command;

fn main() -> std::io::Result<()> {
    let output = Command::new("ls")
        .arg("-la")
        .output()?;

std::process::Command for spawning external processes

rust processes cli
by Marcus Chen 1 tab
rust
use std::ops::Deref;

struct MyBox<T>(T);

impl<T> Deref for MyBox<T> {
    type Target = T;

Deref and DerefMut for smart pointer ergonomics

rust traits smart-pointers
by Marcus Chen 1 tab
rust
fn main() {
    let mut numbers = Vec::new();
    numbers.push(1);
    numbers.push(2);
    numbers.push(3);

Vec<T> for growable arrays with owned data

rust collections
by Marcus Chen 1 tab
rust
use std::mem::MaybeUninit;

fn main() {
    let mut uninit: MaybeUninit<i32> = MaybeUninit::uninit();
    unsafe {
        uninit.as_mut_ptr().write(42);

MaybeUninit for safe uninitialized memory

rust unsafe memory
by Marcus Chen 1 tab
rust
// build.rs
fn main() {
    println!("cargo:rerun-if-changed=build.rs");

    let version = env!("CARGO_PKG_VERSION");
    println!("cargo:rustc-env=BUILD_VERSION={}", version);

Build scripts (build.rs) for compile-time code generation

rust cargo build
by Marcus Chen 1 tab