Smart Pointers
`Box`, `Deref` and `Drop`, `Rc`, `RefCell` and interior mutability, `Weak` and reference cycles, `Cow`.
15 questions
JuniorTheoryCommonWhat does Deref do for Box<T> and String, and what is deref coercion?
What does Deref do for Box<T> and String, and what is deref coercion?
Deref makes a wrapper act like a reference: *b reaches the value in a Box, and String derefs to str. Deref coercion: where &U is expected, the compiler turns &T into &U via deref, so &String passes as &str, at no cost.
Common mistakes
- ✗Thinking
&Stringbecomes&strby copying the bytes, when the compiler only inserts aderefcall - ✗Expecting a coercion in the reverse direction, from
&strto&Stringor from&Tto&mut T - ✗Believing only standard library types may implement
Deref
Follow-up questions
- →Why can a
&Rc<String>be passed to a function that takes&str? - →Why does deref coercion never turn a
&Tinto a&mut T?
JuniorTheoryCommonWhat does the program print (lines separated by spaces)?
What does the program print (lines separated by spaces)?
3 2
Open full question →Common mistakes
- ✗Expecting
3 3:_cbelongs to the inner block, and when the block ends_cis dropped, which lowers the strong count by one. - ✗Expecting
Rc::cloneto copy the value: it adds another owner of the same value and increments the count, and the originalacounts too.
Follow-up questions
- →What would the program print if
let _bwere written aslet _? - →Why do
Rc::clone(&a)anda.clone()do the same thing, and why is the first preferred?
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
1becauseNilends the list: the compiler sizes the type, not the value, and aListstored inline inConsmakes the type infinite (E0072). - ✗Expecting a panic at run time: the size of every type is fixed at compile time, so the error comes from the compiler and the program never starts.
Follow-up questions
- →How would you change the
Consvariant so that the program compiles and prints1? - →Why does a
Box<List>field give theListtype a size the compiler knows?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It compiles and panics
Open full question →Common mistakes
- ✗Expecting a compile error, as with two
&mut:borrow_muttakes&self, soRefCellchecks the rule only at run time, and breaking it is a panic. - ✗Expecting
ato be released after its last use, like a reference: aRefMutguard keeps the borrow until it is dropped, here at the end ofmain.
Follow-up questions
- →Which single line would you add so that the program prints
3? - →How would calling
try_borrow_mutchange what happens on the second borrow?
JuniorTheoryCommonWhen do you need Box<T> in Rust, and what does using one cost?
When do you need Box<T> in Rust, and what does using one cost?
Box<T> puts a value on the heap with one owner. It is needed for a recursive type (else infinite size, E0072), a trait object like Box<dyn Trait>, and moving a big value by copying 8 bytes. It costs one allocation and one indirection.
Common mistakes
- ✗Thinking a value must be boxed to be returned from a function, when returning it by value already moves it
- ✗Expecting a moved
Boxto copy the boxed value rather than the 8-byte pointer - ✗Treating
Boxas garbage collection, though its single owner frees the memory at the closing brace
Follow-up questions
- →Why does
Box<dyn Trait>take 16 bytes whileBox<i32>takes 8? - →Why can
Box::new([0u8; 16 * 1024 * 1024])overflow the stack in a debug build?
MiddleTheoryCommonWhat makes a pointer smart, and how do Box, Rc and Arc differ?
What makes a pointer smart, and how do Box, Rc and Arc differ?
A smart pointer owns its data and implements Deref and Drop. Box has one owner; clone deep-copies the value. Rc and Arc share ownership; clone bumps a count, plain in Rc (one thread only), atomic in Arc (shared by threads).
Common mistakes
- ✗Calling
Rc::clonea copy of the data, when it adds an owner and increments a count - ✗Reaching for
Arcin single-threaded code and paying for atomic operations with no benefit - ✗Forgetting that
StringandVecare smart pointers too: they own a heap buffer and implementDeref
Follow-up questions
- →Why does
thread::spawnreject a closure holding anRc<T>but accept one holding anArc<T>? - →When is
Arc<T>itselfSendandSync, and when is it not?
MiddleTheoryCommonHow do Cell and RefCell differ, and how does RefCell differ from &mut?
How do Cell and RefCell differ, and how does RefCell differ from &mut?
Both change data behind a &T. Cell lends no reference: get copies a Copy value out, set replaces it, at no cost. RefCell lends guards and counts borrows at run time: what &mut forbids at compile time is a panic. Neither is Sync.
Common mistakes
- ✗Believing
RefCelldisables the borrowing rules, when it checks the same rules at run time and panics - ✗Calling
geton aCell<String>, which fails becausegetneedsT: Copy - ✗Putting a
RefCellinside anArcfor threads instead of aMutexor anRwLock
Follow-up questions
- →When would you use
OnceCellinstead of aRefCell<Option<T>>for a lazily filled field? - →What is the thread-safe counterpart of
Rc<RefCell<T>>, and what does it cost?
MiddleCodeCommonWrite a stack on a singly linked list of Option<Box<Node>> links
Write a stack on a singly linked list of Option<Box<Node>> links
push takes the old head with take() and makes it the new node's next; pop takes the head, moves its next into head and returns the value, both O(1). A doubly linked node has two owners: Rc forward plus Weak back, or unsafe.
Common mistakes
- ✗Moving
self.headout of&mut selfwithouttake(), which fails with E0507 - ✗Walking to the tail on every push and losing the O(1) cost
- ✗Adding a
prev: Option<Box<Node>>field, as if aBoxcould have two owners
Follow-up questions
- →Why can dropping a very long
Boxlist overflow the stack, and how would a hand-writtenDropfix it? - →How would
Rcforward links andWeakback links make a doubly linked list work?
MiddleTheoryCommonHow does a cycle of Rc pointers leak memory, and how does Weak break it?
How does a cycle of Rc pointers leak memory, and how does Weak break it?
A parent holding an Rc to a child that holds an Rc back keeps both strong counts at 1 after the outer variables drop, so Drop never runs. Make the back link a Weak (Rc::downgrade): it owns nothing, and upgrade() gives Option<Rc<T>>.
Common mistakes
- ✗Believing Rust never leaks memory, when a cycle of
Rcs is safe code that leaks - ✗Making the child's link to its parent an
Rc, which creates the cycle - ✗Calling
upgrade().unwrap()without handlingNoneafter the parent is gone
Follow-up questions
- →Why is a memory leak not treated as a memory-safety bug in Rust?
- →How does
Rc::new_cyclichelp build a value that refers to itself?
MiddlePerformanceOccasionalWhen does Cow<'a, str> actually save an allocation, and when is it noise?
When does Cow<'a, str> actually save an allocation, and when is it noise?
Cow<'a, str> holds a borrowed &str or an owned String and derefs to str. It saves an allocation when most calls return the input as is, like a normalize that copies only text with tabs. If almost every call builds a string, it is noise.
Common mistakes
- ✗Taking
Cowfor a reference counter or a thread-sharing type, when it is an enum of two variants - ✗Expecting
to_mut()to clone on every call, though it clones once and only a borrowed value - ✗Returning
Cowfrom a function whose result is almost alwaysOwned, gaining nothing but a harder signature
Follow-up questions
- →Why does
String::from_utf8_lossyreturn aCow<str>and not aString? - →When would you return
Cow<'static, str>from a function?
MiddleTheoryOccasionalDeref coercion, AsRef<T> or Borrow<T>: what does each promise to an API?
Deref coercion, AsRef<T> or Borrow<T>: what does each promise to an API?
Deref coercion is implicit, for smart pointers. AsRef<T> is a cheap explicit conversion and no more, so APIs take impl AsRef<Path> to accept &str, String, PathBuf. Borrow<T> also keeps Eq and Hash equal, which HashMap::get needs.
Common mistakes
- ✗Treating
AsRefandBorrowas synonyms, when onlyBorrowpromises the sameEq,OrdandHashas the owned type - ✗Implementing
Derefon a newtype to inherit the inner type's methods instead of writing explicit ones - ✗Taking
&Stringor&PathBufparameters where&strorimpl AsRef<Path>would accept more callers
Follow-up questions
- →Why can
HashMap<String, V>::gettake a&strwithout building aString? - →Why does a generic
impl AsRef<Path>function often forward to an inner function taking&Path?
MiddlePerformanceOccasionalWhy does Arc cost more than Rc, and when do you still pick Rc?
Why does Arc cost more than Rc, and when do you still pick Rc?
Both keep a strong and a weak count in the heap block. Rc changes them with plain adds; Arc with atomic ones, which keep core caches in agreement and cost more, worse under contention. On one thread Rc shares the value for less.
Common mistakes
- ✗Believing
Arclocks the value on every access, when onlycloneanddroptouch the atomic count - ✗Using
Arceverywhere just in case and paying for atomic operations in single-threaded code - ✗Expecting
Arcalone to allow mutation from several threads without aMutexor an atomic type
Follow-up questions
- →Why does the compiler stop an
Rcfrom reaching another thread instead of checking at run time? - →How can a function that only reads the shared value avoid touching the count at all?
MiddleDebuggingOccasionalFix a RefCell already borrowed panic caused by a guard held across a call
Fix a RefCell already borrowed panic caused by a guard held across a call
The Ref from borrow() in the for header lives until the loop ends, and add calls borrow_mut() on the same RefCell inside it. Collect the half prices into a local Vec in one statement, so the guard drops, then call add.
Common mistakes
- ✗Assuming a
Refends at its last use, like a plain reference, instead of when the guard is dropped - ✗Hiding the conflict with
try_borrow_mutand silently losing the writes - ✗Overlooking that a temporary guard in a
forormatchheader lives for the whole loop ormatch
Follow-up questions
- →Why does a
Reftaken in amatchscrutinee live until the end of the wholematch? - →When is
try_borrow_muta correct fix rather than a way to hide the bug?
SeniorTheoryOccasionalWhat do Box<T>, Vec<T>, Rc<T> and Box<dyn Trait> look like in memory?
What do Box<T>, Vec<T>, Rc<T> and Box<dyn Trait> look like in memory?
On 64-bit, Box<T> is one 8-byte pointer to the heap value. Vec<T> is 24 bytes: pointer, capacity, length. Rc<T>/Arc<T> are 8, with both counts in the heap block beside the value. Box<dyn Trait> is 16: data and vtable pointers.
Common mistakes
- ✗Thinking the size of
Box<T>grows withT, when only unsized targets likestrordyn Traitmake it 16 - ✗Placing the
Rccounts next to the pointer on the stack instead of in the heap block - ✗Expecting
Box<dyn Trait>to be one word, forgetting the vtable pointer of a fat pointer
Follow-up questions
- →Why does
Option<Box<T>>take 8 bytes and not 16? - →What does
size_of::<Rc<str>>()report, and why?