Sub topic 2
Deref Coercion, Drop, Rc, and RefCell
Assume you know Rust ownership, borrowing, lifetimes, structs, enums, traits, and stack versus heap memory.
Deref coercion in function calls
The Deref trait defines how a type can be viewed as a reference to another type. Rust uses this trait for deref coercion, which automatically changes a reference to a smart pointer into the reference a function expects.
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(value: T) -> Self {
Self(value)
}
}
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
fn greet(name: &str) {
println!("Hello, {name}!");
}
fn main() {
let name = MyBox::new(String::from("Rust"));
greet(&name);
}The call passes &MyBox<String>. Rust applies Deref to obtain &String, then applies the usual conversion from &String to &str.
Drop and cleanup
A type implementing Drop runs its drop method when its value goes out of scope. Local variables are dropped in reverse declaration order. Use std::mem::drop to end a value's lifetime early.
struct Log(&'static str);
impl Drop for Log {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn main() {
let first = Log("first");
let second = Log("second");
drop(second);
println!("end");
// `first` is dropped here.
}The output is dropping second, end, then dropping first.
Rc: several owners
Rc<T> provides shared ownership for single-threaded programs. Cloning an Rc creates another owner without cloning the stored value. The value is freed when its last strong owner is dropped.
use std::rc::Rc;
fn main() {
let a = Rc::new(String::from("shared"));
let b = Rc::clone(&a);
println!("{}", Rc::strong_count(&a)); // 2
println!("{a} and {b}");
}Interior mutability with RefCell
RefCell<T> enables interior mutability, which means changing a value through a shared reference. It checks borrowing rules at runtime. A conflicting borrow causes borrow_mut to panic, so try_borrow_mut is useful when failure should be handled.
Rc and RefCell together
Rc<RefCell<T>> is useful for shared, mutable data in one thread.
Exercise
Why does Rc<RefCell<Vec<i32>>> allow two owners to push into one vector, while Rc<Vec<i32>> does not?
Show answer
Rc shares ownership, and RefCell supplies runtime-checked mutation. Rc<Vec<i32>> shares an immutable vector.