24 lines
635 B
Rust
24 lines
635 B
Rust
fn main() {
|
|
let mut s1 = String::from("hello");
|
|
|
|
// Mutation by reference requires &mut on both
|
|
// the function declaration and the call site
|
|
change(&mut s1);
|
|
|
|
let len = calculate_length(&s1);
|
|
|
|
println!("The length of '{}' is {}.", s1, len);
|
|
}
|
|
|
|
|
|
fn calculate_length(s: &String) -> usize { // s is a reference to a String
|
|
s.len()
|
|
} // Here, s goes out of scope. But because it does not have ownership of what
|
|
// it refers to, nothing happens.
|
|
|
|
// Change takes a mutable reference
|
|
// only one mutable reference can exist at a time
|
|
fn change(some_string: &mut String) {
|
|
some_string.push_str(", world");
|
|
}
|