borrowing

Rust Deref coercion at a typed boundary

At a suitable coercion site, a reference to a dereferenceable type can adapt to a reference to its target. For String, this lets a caller provide &str without cloning or explicitly calling a conversion method. It is not a general-purpose automatic conversion between unrelated types. Expected output (not executed): Invoice 7 bytes Why: The type annotation supplies the expected &str type. The owned String remains intact. Common mistake: Assuming deref coercion converts an owned String into a new owned value or performs arbitrary type casts.

Formal Syntax & Structure

rust syntaxrust
let text: &str = &owned_string;

Working Example

Example Snippetrust
fn main() {    let owned = String::from("Invoice");    let borrowed: &str = &owned;    println!("{borrowed}");    println!("{} bytes", owned.len());}
Rust Reference