Course contentsShow
← Rust
Lesson 285 of 1,9103. Borrowing and ReferencesFree lesson

Understanding Move vs Borrow

Recognize when an operation necessitates moving ownership versus just a borrow.

Moving vs. Borrowing: Deciding Who Owns the Data

In this lesson, you will learn how to distinguish between transferring full responsibility for data (a move) and simply looking at data temporarily (a borrow).

The Core Difference

In Rust, ownership is like holding a physical book. When you move a variable, you are handing that book to someone else; you no longer have it, and you can’t look at it anymore. When you borrow a variable, you are letting someone read the book, but you still keep ownership of it.

When to Move

You must move ownership when a function or a scope needs to consume the data—meaning it will manage the lifetime of that data, perhaps by destroying it or passing it along to another process.

fn take_ownership(s: String) {
    println!("I own this: {}", s);
} // s is dropped here!

let my_string = String::from("Hello");
take_ownership(my_string);
// println!("{}", my_string); // ERROR: my_string was moved!

In the example above, the function take_ownership takes the String as an argument. By moving it into the function, my_string becomes invalid in the outer scope.

When to Borrow

You should borrow data when you only need to perform an action, like reading a value or calculating a result, without needing to change who "owns" the memory. You signal a borrow using the ampersand (&).

fn inspect(s: &String) {
    println!("I'm just looking at: {}", s);
}

let my_string = String::from("Hello");
inspect(&my_string); // We pass a reference
println!("{}", my_string); // This still works!

Here, inspect asks for a reference (&String). Because we only borrowed the data, the original variable my_string remains perfectly usable after the function call.

How to decide?

Ask yourself: "Does the recipient need to keep this data alive after I’m done with it, or do they just need to process it right now?"

  • If they need to keep it: Move.
  • If they just need to use it briefly: Borrow.

Key Takeaway: Moving transfers ownership and invalidates the original variable, while borrowing provides temporary access without changing ownership.