Rust Ownership Explained: Rules, Move, Clone and E0382
Rust ownership gives every value exactly one owner, so memory is freed automatically when scope ends. You'll walk through the three rules, move semantics, Clone vs Copy, and the E0382 error.

Contents
Rust ownership is the model that determines, at compile time, the owner of a value in memory and when it should be freed. This lesson is written for Rust 1.91 and is part of the Rust: Safe and Fast Programming series. We examine the ownership rules, move semantics, the difference between clone and Copy, and the compiler’s E0382 error with working examples; the Rust borrow checker enforces these rules at compile time.
What you’ll learn in this lesson
- Explain the three rules of ownership
- Distinguish between move and copy
- Read and fix the E0382 error
- Pass values to functions safely and get them back
- See what the Drop trait does at the end of a scope
This lesson assumes you’ve completed the Rust functions and control flow lesson.
What is Rust ownership?
Short answer Rust ownership is a compile-time rule that ensures every value has a single owner and that the value is automatically freed when the owner goes out of scope. This lets Rust provide memory safety without a garbage collector at runtime.
Ownership is the core mechanism that sets Rust apart from other systems languages: the compiler tracks which variable manages which region of memory and rejects rule violations before the program runs. Ownership works together with borrowing and lifetimes; in this lesson we cover only the ownership side.
In practice, this means the compiler answers the question, ‘If I pass this String to a function, will I still have it?’ If the answer is no, the code won’t compile; this strictness prevents memory bugs such as use-after-free, double free, and dangling pointers at compile time. Memory leaks, on the other hand, are considered safe in Rust; ownership makes them harder but does not guarantee against them.
The three rules of ownership
Short answer The Rust ownership rules are three items: every value has exactly one owner, there can be only one owner at a time, and the value is dropped when the owner goes out of scope. These three rules summarize all ownership behavior.
- Every value has an owner. When a
Stringis created, the variable that holds it becomes its owner. - There can be only one owner at a time. If ownership is transferred to another variable, the old one becomes invalid.
- When the owner goes out of scope, the value is dropped. When the scope ends, Rust automatically cleans up the memory.
In the official source, these rules are given in the same order in The Rust Programming Language, chapter 4.1. The rules are short; the hard part is turning them into habits while writing everyday code.
Stack and heap: why it matters
Short answer The stack is a fixed-size and fast memory area, while the heap is flexible but slower; ownership rules largely exist to determine who cleans up data on the heap. Data on the stack goes away automatically with the scope, while data on the heap needs an owner.
The String type is the best example of this distinction: the variable itself sits on the stack with three fields (pointer, length, capacity), and the characters live on the heap. When the variable goes out of scope, Rust cleans up both the stack record and the heap allocation.
| Feature | Stack | Heap |
|---|---|---|
| Size | Known at compile time | Determined at runtime |
| Speed | Very fast, pointer movement | Slower, requires allocation and lookup |
| Cleanup | Automatic at end of scope | Via Drop through the owner |
| Typical types | i32, bool, char, &str |
String, Vec<T>, Box<T> |
That’s why copying types like i32 is nearly free, while copying a String means a new allocation on the heap. The ownership model makes exactly this cost difference visible.
Move: what happens when a value is moved
Short answer Rust move semantics means that when a value is assigned to another variable or passed to a function, ownership is transferred and the old variable becomes invalid. The data on the heap isn’t moved; only the stack record pointing to it is copied to the new variable.
Here’s what happens at the memory level, step by step:
- The line
let s2 = s1;copies the pointer, length, and capacity triple on the stack tos2. - The
merhababytes on the heap aren’t copied; both variables point to the same buffer. - The compiler marks
s1as invalid, so at the end of the scope the buffer is freed only once, throughs2.
A move is a cheap bitwise copy at runtime; its only difference from Copy is that the source becomes invalid.
fn main() {
let s1 = String::from("merhaba");
let s2 = s1; // move: ownership moved to s2
println!("s2 = {}", s2);
let x = 5;
let y = x; // i32 is Copy, so it is copied
println!("x = {}, y = {}", x, y);
let s3 = s2.clone(); // explicit copy
println!("s3 = {}", s3);
}
s2 = merhaba
x = 5, y = 5
s3 = merhaba
In the program above, after the s1 assignment, s1 isn’t used, because ownership has moved to s2. The same line behaves differently for i32: x is still valid because i32 implements the Copy trait.
Reading the E0382 error line by line
The following snippet doesn’t compile because it tries to use a value after it has been moved. The error output was produced with rustc and has been shortened.
fn main() {
let s1 = String::from("merhaba");
let s2 = s1;
println!("{}", s1);
}
error[E0382]: borrow of moved value: `s1`
--> src/main.rs:5:20
|
2 | let s1 = String::from("merhaba");
| -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 | let s2 = s1;
| -- value moved here
4 |
5 | println!("{}", s1);
| ^^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
3 | let s2 = s1.clone();
| ++++++++
- Error code: E0382 means a value was used after it was moved. Here, because
println!borrows the value, the message saysborrow of moved value; if it were an expression that moves the value directly, it would sayuse of moved value. - The
-->line: shows the file, line (5), and column (20) of the error. - Line 2: The reason for the move: the type of
s1isString, andStringdoesn’t implementCopy. - Line 3: The exact point of the move is shown with
--markers and the note "value moved here". - Line 5: The
^^marker points to the expression where the error occurs; here it’s trying to print a value that has been moved. - help block: The compiler suggests a concrete fix: take an explicit copy with
s1.clone().
Learning to read this message saves time; the compiler doesn’t just report the error, it often suggests the fix too. The official explanation of the error code is in the rustc error index.
The difference between Clone and Copy
Short answer The difference between Rust clone and Copy is this: Copy is a marker trait that makes the compiler silently perform a bitwise copy on assignment; Clone is a trait that copies data when you explicitly call .clone(). Copy is only suitable for simple types that live on the stack; types that own heap data can’t be Copy.
| Feature | Copy |
Clone |
|---|---|---|
| Meaning | Implicit bitwise copy | Explicit .clone() call |
| When it kicks in | Assignment, function parameter, return value | Only when called manually |
| Method | None, marker trait | fn clone(&self) -> Self |
| Suitable types | i32, f64, bool, char, &T, tuples and arrays whose elements are all Copy, e.g. (i32, bool), [u8; 4] |
String, Vec<T>, HashMap<K, V> |
| Cost | Very low, stack copy | May involve heap allocation |
You can derive both traits on your own structs; however, to derive Copy, all fields must also be Copy. The official definition is listed on the std::marker::Copy page.
#[derive(Debug, Clone, Copy)]
struct Nokta {
x: i32,
y: i32,
}
Why isn’t String Copy?
String owns a buffer on the heap. If it were Copy, both variables would point to the same buffer during assignment and both would try to free the same memory at the end of the scope; this would lead to a double free error. That’s why Rust provides Clone instead of Copy for String and forces copying to be requested explicitly.
Passing values to functions and getting them back
Short answer If you pass ownership to a function, the value is moved into the function and can’t be used by the caller; to get the value back, the function must return it or you must lend the value with &T.
fn uzunluk_al(s: String) -> usize {
s.len()
}
fn uzunluk_odunc(s: &str) -> usize {
s.len()
}
fn unlem_ekle(mut s: String) -> String {
s.push('!');
s
}
fn main() {
let metin = String::from("sahiplik");
println!("uzunluk: {}", uzunluk_odunc(&metin));
println!("metin hala burada: {}", metin);
let metin = unlem_ekle(metin); // ownership passed in and returned
println!("geri alindi: {}", metin);
println!("uzunluk: {}", uzunluk_al(metin));
}
uzunluk: 8
metin hala burada: sahiplik
geri alindi: sahiplik!
uzunluk: 9
Here three strategies sit side by side: uzunluk_odunc only reads and doesn’t give the value back, unlem_ekle takes ownership, modifies it, and returns it, while uzunluk_al consumes ownership. In real projects, references are preferred for read-only functions; transferring ownership is used only when you truly want to hand the value over to the function.
The uzunluk_al(metin) call on the last line consumes ownership, so metin can’t be used after it:
fn uzunluk_al(s: String) -> usize {
s.len()
}
fn main() {
let metin = String::from("sahiplik");
println!("{}", uzunluk_al(metin));
println!("{}", metin); // error[E0382]: borrow of moved value: `metin`
}
Taking &str instead of &String as a parameter is more flexible; both String and string literals can convert to this type. If you need to give a value to a function and get it back, returning a tuple is also valid:
fn uzunluk_ve_geri(s: String) -> (String, usize) {
let uzunluk = s.len();
(s, uzunluk)
}
This signature works, but it requires unpacking a tuple on every call; in most cases using a reference is simpler. We cover the borrowing rules in the next lesson of the series.
Drop and end of scope
Short answer Rust’s Drop trait is the mechanism that releases the resources of a value whose owner goes out of scope, and it acts as the destructor. The compiler automatically places the drop call at the end of the scope.
struct Kayit {
ad: String,
}
impl Drop for Kayit {
fn drop(&mut self) {
println!("{} kaydı bellekten temizlendi", self.ad);
}
}
fn main() {
let _a = Kayit { ad: String::from("birinci") };
let _b = Kayit { ad: String::from("ikinci") };
{
let _c = Kayit { ad: String::from("ucuncu") };
println!("iç kapsam bitti");
}
println!("dış kapsam bitiyor");
}
iç kapsam bitti
ucuncu kaydı bellekten temizlendi
dış kapsam bitiyor
ikinci kaydı bellekten temizlendi
birinci kaydı bellekten temizlendi
The output order isn’t a coincidence: _c in the inner scope is dropped first, then the outer scope ends. If there are multiple values in the same scope, Rust cleans them up in reverse order of creation (LIFO); that’s why _b is dropped before _a.
Drop order matters for resources such as file handles and locks; releasing resources in reverse order lets dependencies close safely.
If you want to release a value before the scope ends, use std::mem::drop: the call drop(a); consumes a immediately. In contrast, writing a.drop() doesn’t compile; the compiler reports "explicit destructor calls not allowed" with error E0040. Details are in the std::ops::Drop documentation.
Why ownership means Rust doesn’t need a garbage collector
Short answer In Rust, memory is released using ownership and scope information known at compile time rather than a garbage collector tracked at runtime; that’s why there are no GC pauses. The compiler places the release point directly in the generated code.
In languages with a garbage collector, memory is cleaned up at runtime by scanning for reachability. In Rust, the compiler knows statically where each value will be dropped; there’s no extra tracker at runtime. Ownership checking is an example of Rust’s zero-cost abstraction principle: checks finish at compile time and leave no runtime overhead.
| Topic | C++ | Go | Rust |
|---|---|---|---|
| Memory management | Manual; RAII and smart pointers | Garbage collector | Compile-time ownership |
| Release | Destructor | GC | Drop trait |
| Access to moved value | Compiles; the object remains valid but in an indeterminate state (the error isn’t caught by the compiler) | No move concept; assignment copies the value or shares a header pointing to the same data, and the GC manages the memory | Compile error (E0382) |
| Runtime cost | None | May have GC pauses | None |
| Data race checking | Manual, with tools | Runtime race detector | Compile time (Send/Sync) |
The difference in the table explains why Rust promises both C++-like performance and memory safety. The cost is that you talk to the compiler more and write ownership decisions explicitly in your code.
Common Mistakes
1. Using the old variable after a move
Symptom You get the message error[E0382]: borrow of moved value.
Cause The assignment or function call has transferred ownership, so the old binding is no longer valid.
fn main() {
let s1 = String::from("merhaba");
let s2 = s1;
println!("{}", s1); // error: s1 was moved
println!("{}", s2);
}
Fix Use the binding that received the move, or explicitly ask for a copy.
fn main() {
let s1 = String::from("merhaba");
let s2 = s1.clone();
println!("{} {}", s1, s2);
}2. Calling clone everywhere
Symptom The code compiles, but unnecessary heap allocations pile up.
Cause Because clone() is the easiest way to silence the compiler, it becomes a reflex.
fn uzunluk(s: String) -> usize {
s.len()
}
fn main() {
let metin = String::from("sahiplik");
println!("{}", uzunluk(metin.clone()));
}
Fix In functions that only read the value, use an &str parameter; take a copy only when two independent owners are genuinely required.
fn uzunluk(s: &str) -> usize {
s.len()
}
fn main() {
let metin = String::from("sahiplik");
println!("{}", uzunluk(&metin));
}3. Passing a String to a function and then trying to use it
Symptom Printing the same variable after the function call produces E0382.
Cause When the parameter is declared as String, ownership moves into the function.
fn yaz(s: String) {
println!("{}", s);
}
fn main() {
let metin = String::from("merhaba");
yaz(metin);
println!("{}", metin); // error: metin was moved
}
Fix Make the parameter &str and pass a reference at the call site.
fn yaz(s: &str) {
println!("{}", s);
}
fn main() {
let metin = String::from("merhaba");
yaz(&metin);
println!("{}", metin);
}4. Moving a struct field and then using the struct as a whole
Symptom You see the message error[E0382]: borrow of partially moved value: `k`.
Cause When one field is moved to another variable, the struct becomes partially invalid.
#[derive(Debug)]
struct Kullanici {
ad: String,
yas: u32,
}
fn main() {
let k = Kullanici { ad: String::from("Ada"), yas: 30 };
let ad = k.ad;
println!("{:?}", k); // error: k was partially moved
println!("{}", ad);
}
Fix Borrow the field or explicitly copy it, so the struct stays valid as a whole.
#[derive(Debug)]
struct Kullanici {
ad: String,
yas: u32,
}
fn main() {
let k = Kullanici { ad: String::from("Ada"), yas: 30 };
let ad = k.ad.clone();
println!("{:?}", k);
println!("{}", ad);
}Frequently Asked Questions
Why does Rust have ownership?
Ownership exists to provide memory safety and data-race checking with no runtime cost. Before the program even runs, the compiler prevents two owners from pointing at the same memory and prevents access to freed data. This removes the need for a garbage collector.
What is the difference between move and copy in Rust?
A move transfers ownership and invalidates the old binding; a copy creates a new copy of the value and leaves both bindings usable. For types that implement the Copy trait, assignment copies automatically; for other types, it moves. With Clone, you explicitly ask for the copy.
Why isn’t String Copy?
String owns a buffer on the heap; if it were Copy, two variables would point to the same buffer and the same memory would be freed twice at the end of scope. Rust prevents this double-free risk by offering Clone instead of Copy for String.
Does using clone hurt performance?
For heap-owning types like String and Vec, clone() performs a new allocation and copies the data; for Copy types like i32, or inside Rc/Arc, the cost is very low. A clone() called frequently in hot loops creates measurable cost. That’s why references are preferred in functions that only read, and clone() is used when a truly independent copy is needed.
Summary and Next Lesson
- Every value has a single owner; when the owner goes out of scope, the value is cleaned up via
Drop. - Assignment and function calls move by default; the old binding becomes invalid, and trying to use it gives you E0382.
Copyis an implicit, cheap bit copy;Cloneis an explicit, potentially costly copy.- Instead of transferring ownership, borrowing with
&Tor&stris often the right choice. - Thanks to this model, Rust provides memory safety without a garbage collector.
In the next lesson of the series, we cover the rules of borrowing, the inevitable complement to ownership, along with & and &mut references and the errors the Rust borrow checker gives you.
Resources
- doc.rust-lang.org doc.rust-lang.org
Lesson complete · 1 / 1
You've finished this lesson
The next lesson in the series is in the works. Subscribe to the channel so you don't miss it when it's published.
Share it if it helped