Search⌘ K
AI Features

Borrowing a String

Explore how to borrow strings in Rust by modifying functions to accept references instead of owned Strings. Understand the difference between &String and &str, and learn how Rust's deref coercion enables efficient and flexible string handling without unnecessary cloning or memory allocation.

We'll cover the following...

A better solution to the above problem is to modify greet to take a reference.

Exercise Get rid of the .clone() method call, and modify greet to accept a &String parameter. Then fix the calls to the greet function in main.

Rust 1.40.0
fn greet(name: String) {
println!("Hello {}", name);
}
fn main() {
let first_name = "Michael";
let last_name = " Snoyman";
let full_name: String = first_name.to_owned() + last_name;
greet(full_name.clone());
greet(full_name);
}

That’s all well and ...