OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Mutable borrows and non-overlapping use

Change an owned value through a mutable reference.

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

By the end of this lesson

Change an owned value through a mutable reference.

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 11, or be comfortable explaining and running its examples.

Three words to know

Mutable reference
A borrow permitting modification.
Exclusive access
No conflicting references during a mutable borrow’s use.
Scope
The region in which a binding is available.

1. Understand the idea

A helper can change a caller’s String by taking &mut String. The caller must declare the binding mut and pass &mut. Rust prevents simultaneous use of a mutable reference and a conflicting shared reference. Often the right fix is to finish one use before starting the other, rather than clone data or force a more complicated design.

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.

Append through a borrowRUST · save as lesson.rs
fn add_mark(text: &mut String) { text.push_str("!"); }
fn main() {
    let mut greeting = String::from("Hello");
    add_mark(&mut greeting);
    println!("{greeting}");
}
What you should see · example output
Hello!
Compile and run on macOS/LinuxTERMINAL · Bash or Windows PowerShell
rustc --edition=2024 lesson.rs -o lesson
./lesson

3. Explain the result

add_mark borrows greeting exclusively only while it changes it. Once the call finishes, the caller can print greeting again. &mut does not create a second independent String. It provides controlled access to the existing one.

YOUR TURN

A small check before you continue

Why does greeting need mut even though the modification is inside a helper?

Show a suggested answer

The helper changes that same value through &mut. The binding must permit mutation at the call site.

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.