Borrow String when passing to a function
-
&}
-
When passing the variable we need to prefix it with
&
. -
In the function definition we also include the
&
in-front of the type. -
Inside the function we can prefix it with
*
to dereference the variable but in general we don't need to as Rust figures that out.
fn main() { let name = String::from("Foo Bar"); println!("{name}"); greet(&name); println!("{name}"); } fn greet(text: &String) { println!("Greet: {}", *text); // explicit derefernce println!("Greet: {}", text); // automatic dereference println!("Greet: {text}"); }
Foo Bar
Greet: Foo Bar
Greet: Foo Bar
Greet: Foo Bar
Foo Bar