Rust · Course navigation

Rust Ownership

Borrow a string without moving it.

On this page

The concept

A String owns its heap allocation. Passing &name borrows it for the function call, so the caller can still use name afterward.

Code example

Rust
fn show(value: &str) {
    println!("{}", value);
}
fn main() {
    let name = String::from("Ada");
    show(&name);
    println!("{}", name);
}
Output
Ada
Ada

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1fn show(value: &str) {
2 println!("{}", value);
3}
4fn 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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

Behind the scenes

How Rust processes this code

Rust checks types and ownership at compile time, then builds a native executable.