Skip to content
เข้าสู่ระบบ

Smart Pointers Pattern

Patterns สำหรับ smart pointer types ใน Rust ที่ manage memory และ ownership

Box<T> allocate data บน heap แทน stack สำหรับ recursive types และ trait objects

fn main() {
// Simple heap allocation
let boxed = Box::new(42);
println!("Boxed: {}", *boxed);
// For recursive types
#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
let list = List::Cons(1,
Box::new(List::Cons(2,
Box::new(List::Cons(3,
Box::new(List::Nil))))));
println!("List: {:?}", list);
// For trait objects
trait Animal {
fn speak(&self);
}
struct Dog;
impl Animal for Dog {
fn speak(&self) { println!("Woof!"); }
}
let animal: Box<dyn Animal> = Box::new(Dog);
animal.speak();
// Box::leak for static lifetime
let static_str: &'static str = Box::leak(String::from("forever").into_boxed_str());
println!("Static: {}", static_str);
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด