Rust Simple Deref example


Deref has a simple rule: if you have a type T and it implements Deref<Target=F>, then &T coerces to &F, compiler will repeat this as many times as needed to get F, for example:

fn f(x: &str) -> &str { x }
fn main() {
    // Compiler will coerce &&&&&&&str to &str and then pass it to our function
    f(&&&&&&&"It's a string"); 

Deref coercion is especially useful when working with pointer types, like Box or Arc, for example:

fn main() {
    let val = Box::new(vec![1,2,3]);
    // Now, thanks to Deref, we still 
    // can use our vector method as if there wasn't any Box
    val.iter().fold(0, |acc, &x| acc + x ); // 6
    // We pass our Box to the function that takes Vec,
    // Box<Vec> coerces to Vec

fn f(x: &Vec<i32>) {
    println!("{:?}", x) // [1,2,3]