OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Shared references and borrowing

Pass a borrowed string to a function while keeping ownership.

Lesson 11 of 30 · About 20 minutes · Beginner · English

By the end of this lesson

Pass a borrowed string to a function while keeping ownership.

Before you start

  • Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
  • Complete lesson 10, or be comfortable explaining and running its examples.

Three words to know

Reference
A borrowed view of a value.
Borrow
Temporary access without taking ownership.
Shared reference
A reference that does not permit mutation through it.

1. Understand the idea

Writing &value creates a borrow. A function accepting &str can inspect owned String data without taking ownership or allocating a clone. The referenced data must remain valid while it is used. Rust checks that relation at compile time. A shared reference also prevents conflicting mutation for the duration of the borrow’s use.

2. Save, run and observe

Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.

Inspect without movingRUST · save as lesson.rs
fn byte_length(value: &str) -> usize { value.len() }
fn main() {
    let title = String::from("Rust");
    println!("bytes={}", byte_length(&title));
    println!("still owned: {title}");
}
What you should see · example output
bytes=4
still owned: Rust
Compile and run on macOS/LinuxTERMINAL · Bash or Windows PowerShell
rustc --edition=2024 lesson.rs -o lesson
./lesson

3. Explain the result

&title can be used where &str is expected. byte_length returns a number, so no reference escapes the call. title can be printed afterwards because the function never took ownership. The helper measures bytes; its name deliberately avoids claiming to count visible characters.

YOUR TURN

A small check before you continue

Change the helper to accept String by value and pass title without &: will the later println still compile?

Show a suggested answer

No. Passing title by value moves it. Use borrowing when the function only needs to read.

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.