What Is Coercion in Rust (Deref Coercion, Unsized Coercion)?

Coercion in Rust automatically converts smart pointers to references and sized types to slices, enabling seamless function calls without explicit casting.

Coercion in Rust is the compiler's automatic conversion of one type to another to satisfy function signatures, primarily through Deref coercion (smart pointers to references) and unsized coercion (sized types to slices). Deref coercion allows you to pass a Box<T> or &String where a &T or &str is expected, while unsized coercion lets you pass a String where a &str is needed. This happens implicitly, so you rarely need to write explicit conversion code.

use std::ops::Deref;

struct Wrapper(String);

impl Deref for Wrapper {
    type Target = String;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

fn takes_str(s: &str) {
    println!("{s}");
}

fn main() {
    let wrapper = Wrapper("Hello".to_string());
    // Deref coercion: Wrapper -> &String -> &str
    takes_str(&wrapper);
    
    let s = String::from("World");
    // Unsized coercion: String -> &str
    takes_str(&s);
}