std-method

String::as_str

Borrow the existing text without creating another owned buffer. The borrow cannot outlive the owner. Expected stdout (not executed): Laleh Laleh Common mistake: Treating the returned slice as an independent owned copy.

Formal Syntax & Structure

rust syntaxrust
fn as_str(&self) -> &str

Working Example

Example Snippetrust
fn main() {    let name = String::from("Laleh");    let view = name.as_str();    println!("{view} {name}");}
Rust Reference