Ownership
Stack and heap, the three ownership rules, moves, `Copy` and `Clone`, `Drop`, and how ownership travels through function calls.
17 questions
JuniorTheoryCommonWhat does the program print?
What does the program print?
hi! hi
Open full question →Common mistakes
- ✗Expecting
hi! hi!:cloneon aStringallocates a separate buffer, so a later change tos1never shows up ins2. - ✗Expecting
cloneto moves1intos2: it copies the contents into a newString, ands1keeps its own string and stays usable.
Follow-up questions
- →What changes if you replace
s1.clone()with&s1? - →Why does Rust make you write
.clone()instead of copying aStringon assignment?
JuniorTheoryCommonWhat does the program print?
What does the program print?
5 5
Open full question →Common mistakes
- ✗Expecting a compile error, as with a
String:i32implementsCopy, solet b = a;duplicates the value andastays usable. - ✗Expecting
0 5: copying readsaand leaves it untouched, so both variables hold5.
Follow-up questions
- →Which other types behave like
i32here, and which behave likeString? - →What would happen if
aheldString::from("5")instead of5?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
hi hi: a parameter of typeStringtakes ownership of the argument, so aftertake(s)the variablesis moved and cannot be used. - ✗Expecting the string to come back when
takereturns: it is freed at the end oftake; to keep it, return it fromtakeor passs.clone().
Follow-up questions
- →How would you change
takeso thatmaincan still printsafter the call? - →What would change if
takereturned theStringit received?
JuniorTheoryCommonAfter let b = a;, is a still usable when it holds a String, and when an i32?
After let b = a;, is a still usable when it holds a String, and when an i32?
For a String, let b = a; is a move: the header is copied, b becomes the owner, and using a later fails with E0382. An i32 is Copy, so it is duplicated and a stays valid. A move hands over ownership and disables the source.
Common mistakes
- ✗Believing a moved
Stringbecomes empty: it is not empty but unusable, and no destructor runs for it - ✗Thinking
let b = a;copies the heap bytes of aString: only the pointer, length and capacity are copied - ✗Expecting every type to move: types that implement
Copy, such asi32, are duplicated instead
Follow-up questions
- →Which operations besides
letmove a value out of a variable? - →Can a moved-from
mutvariable be given a new value and used again?
JuniorTheoryCommonWhat are the three ownership rules, and how is memory freed without a garbage collector?
What are the three ownership rules, and how is memory freed without a garbage collector?
Each value has an owner, there is exactly one owner at a time, and when the owner goes out of scope the value is dropped. The compiler inserts the destructor call there, so heap memory is freed deterministically, with no run-time collector.
Common mistakes
- ✗Calling ownership a compile-time garbage collector: nothing is collected, the compiler inserts a destructor call where the owner's scope ends
- ✗Thinking values live until the function returns: a value is dropped at the end of the block in which its owner was declared
- ✗Believing the programmer must call
dropby hand: the destructor call is inserted automatically
Follow-up questions
- →What happens to the strings inside a
Vec<String>when the vector is dropped? - →Which C memory bugs do these rules rule out, and which can still happen?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
hi hi:Stringis notCopy, solet s2 = s1;hands ownership tos2and leavess1unusable; keeping both takeslet s2 = s1.clone();. - ✗Expecting a panic at run time: the compiler tracks every move and stops the build with
error[E0382]: borrow of moved value: `s1`.
Follow-up questions
- →How would you change the program so that it prints
hi hi? - →Why does the same code compile when
s1holds ani32instead of aString?
MiddleTheoryCommonCopy vs Clone: how do they differ, and which types are allowed to be Copy?
Copy vs Clone: how do they differ, and which types are allowed to be Copy?
Copy is an implicit bitwise copy on assignment and passing, with no code of its own; Clone is an explicit .clone() whose cost the type decides, often a deep copy. Only a type whose fields are all Copy and that has no Drop may be Copy.
Common mistakes
- ✗Treating
Copyas a fastClone: it has no method to override and only promises that a bitwise copy is a correct duplicate - ✗Assuming
cloneis always deep: what it does is up to the type, andRc::cloneonly increments a counter - ✗Believing a type with its own
Dropcan beCopywhen all its fields are:DropandCopyexclude each other (E0184)
Follow-up questions
- →Why is a shared reference
&TalwaysCopywhile&mut Tnever is? - →What breaks for users of a public type if you later remove
Copyfrom it?
MiddleDebuggingCommonFix a String that is moved into a function on every pass of a loop
Fix a String that is moved into a function on every pass of a loop
The first call moves word into shout, so the next pass uses a moved value (E0382). Borrowing fixes it: take &str and call shout(&word). A clone allocates on every pass, and handing the String back works but clutters every call.
Common mistakes
- ✗Reaching for
.clone()by reflex: it allocates a new buffer on every pass when a borrow is enough - ✗Believing
mutlets a moved value be used again: a movedmutbinding must be given a new value first - ✗Handing the argument back in a tuple when the function only needs to read it
Follow-up questions
- →Why is
&stra better parameter type than&Stringforshout? - →When is moving the
Stringinto the function the right design after all?
MiddleTheoryCommonWhy ownership instead of a garbage collector or free, and which bugs does it rule out?
Why ownership instead of a garbage collector or free, and which bugs does it rule out?
Ownership frees memory deterministically, with no collector pauses or run-time cost, and the compiler checks it: safe code has no use-after-free, double free or dangling references, and with the borrow rules no data races. Leaks stay possible.
Common mistakes
- ✗Claiming ownership prevents memory leaks:
Rccycles,mem::forgetandBox::leakall leak in safe code - ✗Thinking the safety costs run time: ownership and borrowing are checked only during compilation
- ✗Forgetting data races: the borrow rules that stop dangling references also stop unsynchronised shared mutation
Follow-up questions
- →Why does Rust not count a memory leak as a memory-safety violation?
- →Which of these guarantees stop holding inside an
unsafeblock?
MiddleTheoryCommonHow does Drop implement the cleanup idiom RAII, and in what order are values dropped?
How does Drop implement the cleanup idiom RAII, and in what order are values dropped?
A type's Drop::drop runs by itself when its owner leaves scope, so files, locks and buffers are released with no explicit call, even in a panic. Locals drop in reverse declaration order; fields after the struct's own drop, in declaration order.
Common mistakes
- ✗Expecting locals to be dropped in declaration order: the last one declared is dropped first
- ✗Thinking destructors are skipped on a panic: they run while the stack unwinds
- ✗Believing fields are dropped before the struct's own
drop: thatdropruns first, then the fields in declaration order
Follow-up questions
- →Why does
let _ = guard();release a lock at once, whilelet _g = guard();does not? - →In which cases does a destructor not run at all, even though the owner is gone?
JuniorTheoryOccasionalStack or heap: where do i32, String, Vec<T> and Box<T> keep their data?
Stack or heap: where do i32, String, Vec<T> and Box<T> keep their data?
An i32 lives wholly on the stack. String and Vec<T> keep a three-word header (pointer, length, capacity) where the variable is and their contents on the heap; Box<T> is one pointer to a heap value. The owner frees its heap part too.
Common mistakes
- ✗Saying a
Stringlives on the heap: only its bytes do, while the header stays where the variable is - ✗Believing
Box<T>stores its value inline: it is a single pointer, and the value itself is on the heap - ✗Assuming the heap part must be freed by hand once the stack part is gone: the owner frees both
Follow-up questions
- →Why does
size_of::<String>()return 24 no matter how long the text is? - →Where does the header of a
Stringstored inside aVec<String>live?
MiddleTheoryOccasionalWhy can a type not implement both Copy and Drop, and what would break if it could?
Why can a type not implement both Copy and Drop, and what would break if it could?
Copy promises a bitwise duplicate is a full, independent value; Drop means the value owns something to release. Every duplicate of a Drop type would run the destructor on the same resource, a double free, so rustc rejects the pair (E0184).
Common mistakes
- ✗Treating
Copyas just a cheapClone: it promises that duplicates need no cleanup of their own, which aDroptype cannot promise - ✗Expecting only fields to matter: a type whose fields are all
Copystill cannot beCopyonce it has its ownDrop - ✗Assuming duplicates would share one destructor call: each copy would run
dropon the same resource
Follow-up questions
- →How does the same reasoning forbid
Copyfor a struct with aStringfield (E0204)? - →Why may a type with its own
Dropstill implementClone?
MiddleTheoryOccasionalWhy can't you call x.drop() directly, and what do mem::drop and mem::forget do?
Why can't you call x.drop() directly, and what do mem::drop and mem::forget do?
x.drop() is refused (E0040) because x would stay the owner and be dropped again at scope end. std::mem::drop(x) takes ownership and lets its parameter go out of scope, so the destructor runs now; mem::forget(x) takes it and never runs it.
Common mistakes
- ✗Trying
x.drop()withlet mut x: E0040 still applies, becausexwould remain the owner and be dropped twice - ✗Thinking
mem::dropis compiler magic: it is an ordinary function that takes ownership and lets its parameter go out of scope - ✗Expecting
mem::forgetto free the memory without runningDrop: it runs nothing, so a buffer the value owned leaks
Follow-up questions
- →What does
drop(x)do whenxis ani32, and why does the compiler warn about it? - →When is
mem::forgetused on purpose, for example with a handle passed to C code?
MiddleDebuggingOccasionalFix a method that moves a field out of &mut self
Fix a method that moves a field out of &mut self
Through &mut self the method may change items but not take it, or the struct would hold a moved-out field. mem::take(&mut self.items) returns the vector and leaves an empty one; mem::replace leaves a value you pick; mem::swap swaps two.
Common mistakes
- ✗Cloning the whole vector to satisfy the compiler: it copies every string when
mem::takejust puts an emptyVecin place - ✗Reaching for
unsafeto move a field out:mem::takeandmem::replaceare safe and leave the field valid - ✗Expecting
mem::taketo work for any type: it needsDefault; otherwise usemem::replacewith an explicit value
Follow-up questions
- →How does
Option::takesolve the same problem for anOption<T>field? - →When is changing the method to take
selfby value the better fix?
MiddleTheoryOccasionalCan safe Rust leak memory, and why is a leak not undefined behaviour?
Can safe Rust leak memory, and why is a leak not undefined behaviour?
Yes. Rc values pointing at each other in a cycle never reach a zero count, mem::forget skips the destructor, and Box::leak keeps a value alive on purpose, all in safe code. A leak wastes memory but cannot corrupt it, so safe Rust allows it.
Common mistakes
- ✗Claiming Rust guarantees no leaks: the guarantee is about memory safety, not about every allocation being freed
- ✗Believing
mem::forgetneedsunsafe: it is a safe function, because skipping a destructor cannot corrupt memory - ✗Expecting
Rcto detect cycles: reference counting has no cycle collector, so a cycle keeps its counts above zero forever
Follow-up questions
- →How does a
Weakpointer let a parent and its children refer to each other without a leak? - →Why is
Box::leakhandy for configuration data that must live for the whole program?
MiddleTheoryOccasionalWhere do a String's header and bytes live, and what exactly does a move copy?
Where do a String's header and bytes live, and what exactly does a move copy?
A String is a three-word header (pointer, length, capacity) where the variable lives, plus its bytes in a heap buffer. A move copies only that header, 24 bytes on 64-bit, and disables the source; the buffer stays, so cost never grows with length.
Common mistakes
- ✗Saying a move copies the string: the heap bytes stay where they are and only the header is copied
- ✗Believing the source is nulled at run time: the compiler tracks the move and simply never drops the source
- ✗Expecting C++-style move constructors: a Rust move is always a plain bitwise copy and cannot be customised
Follow-up questions
- →Where does the header of a
Stringstored inside aVec<String>live? - →When does the compiler need a hidden drop flag for a moved variable?
SeniorTheoryOccasionalWhat is drop glue, and in what order are locals, fields and temporaries dropped?
What is drop glue, and in what order are locals, fields and temporaries dropped?
Drop glue is compiler-generated code that runs a type's own Drop::drop, then drops each field, so drop sees intact fields. Locals drop in reverse declaration order; fields and tuple or array elements front to back; a temporary at the end of its statement.
Common mistakes
- ✗Expecting fields to be dropped before the type's own
drop: the impl runs first, then the fields in declaration order - ✗Assuming locals and fields share one order: locals drop last-declared first, fields and elements first to last
- ✗Thinking a temporary lives to the end of the block: it is dropped at the end of its statement unless a
letextends its lifetime
Follow-up questions
- →How did edition 2024 change when temporaries in a block's tail expression are dropped?
- →Why may you not move a field out of a value whose type implements
Drop(E0509)?