How to Use the Delegation Pattern in Rust

Implement the Deref trait in Rust to delegate method calls from a wrapper struct to its inner value.

Use the Deref trait to implement delegation in Rust, allowing a custom type to behave like the type it wraps. Define a struct holding the wrapped value and implement Deref to return a reference to it, enabling automatic method calls on the inner type.

use std::ops::Deref;

struct MyBox<T>(T);

impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> {
        MyBox(x)
    }
}

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

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

fn main() {
    let x = 5;
    let y = MyBox::new(x);
    println!("y = {}", *y); // Calls deref automatically
}