Borrowing a String
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
.
Press + to interact
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 good, but let’s make our example a little more involved. Now we want to greet a few different people:
Press + to interact
fn greet(name: &String) {println!("Hello {}", name);}fn main() {let snoyman: &str = " Snoyman";let michael: String = "Michael".to_owned() + snoyman;let miriam: String = "Miriam".to_owned() + snoyman;let alice: &str = "Alice Smith";greet(&michael);greet(&miriam);greet(alice);}
Both michael
and miriam
...