traits

rust
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let data = Arc::new(Mutex::new(vec![1, 2, 3]));

Send and Sync traits for safe concurrency guarantees

rust concurrency traits
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
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
struct UserId(u32);

impl From<u32> for UserId {
    fn from(id: u32) -> Self {
        UserId(id)
    }

From and Into for type conversions

rust traits conversion
by Marcus Chen 1 tab
rust
use std::fmt;

struct Point {
    x: i32,
    y: i32,
}

std::fmt::Display for user-facing string representations

rust traits formatting
by Marcus Chen 1 tab
rust
trait Container {
    type Item;
    fn get(&self, index: usize) -> Option<&Self::Item>;
}

struct Warehouse {

Associated types in traits for cleaner generics

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

fn print_it<T: Display>(value: T) {
    println!("Value: {}", value);
}

Trait bounds for generic functions with behavior constraints

rust traits generics
by Marcus Chen 1 tab
rust
use std::path::Path;

fn process_file(path: impl AsRef<Path>) {
    let path = path.as_ref();
    println!("Processing: {}", path.display());
}

AsRef and AsMut for flexible function parameters

rust traits conversion
by Marcus Chen 1 tab
rust
#[derive(Default, Debug)]
struct Config {
    host: String,
    port: u16,
    debug: bool,
}

Default trait for sensible zero values

rust traits
by Marcus Chen 1 tab
rust
#[derive(Debug, Clone, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

Derive macros for automatic trait implementations

rust macros traits
by Marcus Chen 1 tab
rust
struct Logger {
    name: String,
}

impl Drop for Logger {
    fn drop(&mut self) {

Drop trait for custom cleanup logic

rust traits memory-management
by Marcus Chen 1 tab
rust
fn print_size<T: ?Sized>(value: &T) {
    // Can accept both &str and &String
    println!("Value: {:p}", value as *const T as *const ());
}

fn main() {

Sized trait and ?Sized for dynamically-sized types

rust traits types
by Marcus Chen 1 tab