Rust notes
Who owns this string?
A short experiment with borrowing, a compiler message, and one small change.
Create a string and hand it to a function that takes a String. Try printing it again after the call. Rust reports that the value has moved because the function now owns the allocation.
Borrow it for the greeting
fn greet(name: &str) {
println!("Bonjour, {name}!");
}
fn main() {
let name = String::from("Douala");
greet(&name);
println!("{name}");
}
The parameter describes what the function needs. A shared reference lets it read the text while the caller keeps ownership.
Comments
Share your thoughts with the community on GitHub.