Rust course Lesson 3 of 6

Rust from zero: clone when two names need the text

Assigning a String moves it. The old name cannot use it. clone keeps both. The program prints latte latte.

Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.

Back to top

A String has one owner. let b = a moves the string to b. After the move, a cannot be used. The compiler stops you. A second cup that needs the same drink name calls clone, and each name owns its own copy.

Move transfers the owner#

A String has one owner. let b = a moves the owner from a to b, and the compiler then refuses to use a. That is the protection: two names cannot both free the same buffer. clone allocates a second buffer and copies the bytes, so a and b are both valid and the program can print both. Cloning is the explicit cost. The borrow checker is what makes the move version fail at compile time instead of freeing the memory twice.

clone makes a second String
  1. alatte
  2. blatte
fn main() {
    let a = String::from("latte");
    let b = a.clone();
    println!("{a} {b}");
}
latte latte

clone is the copy you asked for#

String::from("latte") owns the drink name. a.clone() allocates a second String with the same bytes and moves that one into b. a still owns the first. Both can be printed, so two tickets can carry the same word.

Delete .clone() and the program does not compile. The error says a was moved and later used. That error is the tip, delivered before the program runs. An i32 does not need clone for this, because assigning an i32 copies the number. The price 450 can be copied by assignment. The types that own heap data, String among them, move.

Borrow when you only need to look#

fn show(s: &str) can take &a and look at the text without moving it and without cloning. Clone when the other owner must keep the text after you are gone. Borrow when they only need to read it during the call. The next lesson changes a field through a method, which means the method needs a mutable borrow.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.