पाठ 7 / 25
Ownership and Moves
One owner at a time.
Moving transfers responsibility
Each value has exactly one owner; when the owner goes out of scope, the value is dropped (memory freed, files closed). Assigning a heap-owning value like String or Vec to another variable, or passing it to a function, moves ownership: the original variable can no longer be used. This is how Rust guarantees each value is freed exactly once without a garbage collector. Simple types such as integers implement Copy and are copied instead of moved.
The heart of Rust
Every value has one owner; references borrow without taking ownership, under rules the compiler enforces.
Using a value after it moved, compile error
I compiled this with Rust 1.99.0 (cargo build); it is meant to fail. The output is trimmed to the error lines. The compiler reports E0382 "borrow of moved value", points at the use after the move and at the function that took ownership, and suggests cloning.
fn consume(s: String) {
println!("consumed {s}");
}
fn main() {
let name = String::from("Asha");
consume(name); // ownership moves into consume
println!("{name}"); // error: name was moved
}
Output:
error[E0382]: borrow of moved value: `name` --> src/main.rs:8:16 --> src/main.rs:1:15 help: consider cloning the value if the performance cost is acceptable error: could not compile `demo` (bin "demo") due to 1 previous error
Borrow instead of moving
If a function only needs to read a value, take &String or better &str, so the caller keeps ownership.
त्वरित जाँच: What happens to a String passed by value to a function?
- Ownership moves into the function; the caller can no longer use it
- It is copied automatically
- It becomes a global variable
- Nothing; both can use it
Answer
Ownership moves into the function; the caller can no longer use it — Moves transfer ownership.