Rullst AcademyRullst Academy/Lesson
Rust: from idea to program · Lesson 06 / 08

Borrow without losing the text

You want to show the robot’s name in two messages. A function can read the text without taking ownership of it.

Learning paths11 min

Let's discover together

  1. 1

    String owns text that can be built while the program runs. let name = String::from("Robo"); creates that value and makes name its owner.

  2. 2

    Passing name to a function that takes String moves the value into it. Without getting it back, we cannot continue using the old binding. The compiler checks this rule.

  3. 3

    A function taking &str only needs to read text. Calling show(&name) borrows it: Rust allows this String reference where &str is expected. The function does not take ownership of name.

  4. 4

    name.clone() creates another String with its own text. That differs from borrowing. Integers such as u32 are Copy: copying them does not follow String’s move behavior.

✦
YOUR MISSION

Choose a text borrow and distinguish moving, borrowing and explicitly cloning.

Now it's your turn

Discovery workshop

Two messages, one name

We have let name = String::from("Robo"); and fn show(name: &str). We want to call show and then use name again.
Your snippet in progress
let name = String::from("Robo");
show({1});
println!("{name}");
Build your answers and check when you are ready.
A moment to understand

If the function only needs to read the name, which interface expresses that intent?

I need a hint

A reference allows reading without taking ownership of the text.

Loading your journey…

Take it with you

Explain why borrowing text is enough to print it. In the final project, find the function taking &str and identify who still owns the String.

Show me the Rust behind it

This part is optional. You don't need to memorize the code to continue.

fn show(name: &str) {
    println!("{name}");
}

fn main() {
    let name = String::from("Robo");
    show(&name);
    println!("{name}");
}
At your own pace

My files and GitHub

Every lesson can become your own record: code, notes or a practice plan. Saving a file to GitHub is optional and does not change your XP.

Student guide

The editor and downloads open when this lesson is available to your account. Check access below or return to the track map.

Checking your access to this lesson…

Rullstpetbot

AI can make mistakes. Check the lesson material.