In this lesson, you will learn how the Rust compiler performs "invisible" type conversions to make passing references to functions more flexible.
The Magic of Coercion
Usually, Rust is very strict about types. If a function asks for a &String, you might assume you must pass a &String. However, Rust’s Reference Coercion rules allow the compiler to automatically convert certain types into others if it is safe to do so. This prevents you from having to manually transform your data every time you call a function.
The most common example is "Deref Coercion." When you have a type that implements the Deref trait (like String or Vec<T>), Rust can automatically turn a reference to that type into a reference to its underlying data type (like &str or &[T]).
How It Works
Consider this code:
fn print_length(s: &str) {
println!("Length is {}", s.len());
}
fn main() {
let my_string = String::from("Hello!");
// We pass a &String, but the function expects a &str.
// Rust automatically coerces &String into &str for us!
print_length(&my_string);
}
In the example above, &my_string is technically a &String. The function print_length expects a &str. Without coercion, you would have to write print_length(&my_string[..]) every single time. Because Rust knows how to convert a String into a str via the Deref trait, it performs the conversion for you automatically.
Why This Matters
Reference coercion makes your code significantly cleaner and more ergonomic. It allows you to write functions that accept the most general form of a type (like &str instead of &String) while still allowing users to pass in more specific, owned types without extra syntax. The compiler is essentially looking at your code, seeing that the types don't perfectly match, checking if a valid conversion exists, and applying it behind the scenes so the borrow checker stays happy.
Key Takeaway: Reference Coercion allows the compiler to automatically transform a reference from one type to another—such as converting &String to &str—to satisfy function requirements without manual intervention.