Smart Pointers: Box, Rc, RefCell – Rust
Heap memory, shared ownership, interior mutability, and trait objects.
A smart pointer is a pointer with additional behavior (it implements Deref and usually Drop). Box<T> puts a value on the heap and is its sole owner. Typical uses: recursive types and trait objects.
enum Liste {
Cons(i32, Box<Liste>), // without the Box the type would have infinite size
Nil,
}
use Liste::{Cons, Nil};
fn summe(l: &Liste) -> i32 {
match l {
Cons(x, rest) => x + summe(rest),
Nil => 0,
}
}
fn main() {
let l = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
println!("{}", summe(&l)); // 6
}With Box<dyn Trait> you store different types behind the same trait in one collection (dynamic dispatch via a vtable, similar to virtual methods in C++):
trait Form {
fn flaeche(&self) -> f64;
}
struct Kreis(f64);
struct Quadrat(f64);
impl Form for Kreis {
fn flaeche(&self) -> f64 { 3.14 * self.0 * self.0 }
}
impl Form for Quadrat {
fn flaeche(&self) -> f64 { self.0 * self.0 }
}
fn main() {
let formen: Vec<Box<dyn Form>> = vec![Box::new(Kreis(1.0)), Box::new(Quadrat(2.0))];
let summe: f64 = formen.iter().map(|f| f.flaeche()).sum();
println!("{:.2}", summe); // 7.14
}Rc<T> (reference counting) allows multiple owners within one thread. RefCell<T> moves the borrow check to runtime (“interior mutability”): a violation of the rules then leads to a panic instead of a compiler error. Together, Rc<RefCell<T>> gives you shared, mutable data.
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let geteilt = Rc::new(RefCell::new(vec![1, 2]));
let a = Rc::clone(&geteilt); // only the counter goes up
a.borrow_mut().push(3);
println!("{:?} {}", geteilt.borrow(), Rc::strong_count(&geteilt)); // [1, 2, 3] 2
}The Drop trait lets you write your own cleanup code, which is Rust's equivalent of destructors (RAII). It runs automatically at the end of the scope, in reverse order of declaration:
struct Wache(&'static str);
impl Drop for Wache {
fn drop(&mut self) {
println!("{} gone", self.0);
}
}
fn main() {
let _a = Wache("A");
let _b = Wache("B");
println!("End");
}
// Output: End / B gone / A goneRc references are never freed (memory leak). For back-references, use Weak<T> (Rc::downgrade), for example in parent-child trees.Rc<RefCell<...>> everywhere, that is often a sign of a design that works against ownership. First check whether indices, copies, or clear ownership relationships would be simpler.