Rust Ownership
Borrow a string without moving it.
Rust
fn show(value: &str) {
println!("{}", value);
}
fn main() {
let name = String::from("Ada");
show(&name);
println!("{}", name);
}Output
Ada Ada
Explanation
A String owns its heap allocation. Passing &name borrows it for the function call, so the caller can still use name afterward.
Explore the dry run
Guided walkthroughReady
1
fn show(value: &str) {2
println!("{}", value);3
}4
fn main() {5
let name = String::from("Ada");6
show(&name);7
println!("{}", name);8
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Allocate an owned String. | name = String("Ada") | — | |
| Borrow name and call show; ownership stays in main. | name = String("Ada") | — | |
| show prints the borrowed string. | name = String("Ada") | Ada | |
| main still owns name and prints it again. | name = String("Ada") | Ada Ada |