Rust: Memory – code examples
Contents
Trait objects with Box<dyn Trait>
Memory#box#dyn#trait-object
Use case: Keeping different types with the same behavior in one list (plugins, shapes, handlers).
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
}dyn Form means dynamic dispatch (vtable). Box is needed because the elements have different sizes.
Shared mutable data (Rc<RefCell>)
Memory#rc#refcell#smart-pointer
Use case: Several owners modifying the same data structure (graphs, GUI state) within one thread.
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let geteilt = Rc::new(RefCell::new(vec![1, 2]));
let a = Rc::clone(&geteilt);
a.borrow_mut().push(3);
println!("{:?} {}", geteilt.borrow(), Rc::strong_count(&geteilt)); // [1, 2, 3] 2
}Rc counts owners, and RefCell checks borrowing at runtime (panic on a rule violation). For threads, use Arc<Mutex<T>> instead.
Function with a lifetime annotation
Memory#lifetime#reference
Use case: Returning references that depend on several inputs (search, longest text).
fn laengerer<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let x = String::from("Rust");
let y = String::from("Swift");
println!("{}", laengerer(&x, &y)); // Swift
}'a says: the result lives at most as long as the shorter-lived input. Without the annotation, the compiler rejects the signature.