References allow you to refer to a value without taking ownership - this is called borrowing.
| Type | Syntax | Can Modify? | How Many? |
|---|---|---|---|
| Immutable | &T | No | Unlimited |
| Mutable | &mut T | Yes | Only one |
fn calculate_length(s: &String) -> usize {
s.len()
} // s goes out of scope, but doesn't drop the String
let s = String::from("hello");
let len = calculate_length(&s); // s is still valid!fn add_world(s: &mut String) {
s.push_str(" world");
}
let mut s = String::from("hello");
add_world(&mut s); // s is now "hello world"You can have either ONE mutable reference OR any number of immutable references - never both at once!
Implement two functions:
add_suffix - takes &mut String and appends "_modified"get_length - takes &String and returns the lengthadd_suffix should modify the string in placeget_length should not take ownershiprust_modified 13s.push_str("_modified") to appends.len() to get length&mut for mutable, & for immutable