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

Box Smart Pointer

Box เป็น smart pointer พื้นฐานที่สุด สำหรับ heap allocation และ single ownership

Box<T> เก็บ data บน heap แทน stack:

  • Single owner (ไม่ share ownership)
  • ใช้สำหรับ recursive types
  • ใช้สำหรับ trait objects (Box<dyn Trait>)
  • ใช้สำหรับ large data
fn main() {
// ============================================
// Box basics
// ============================================
// Allocate on heap
let boxed = Box::new(42);
println!("Boxed: {}", boxed);
// Deref to access
let value: i32 = *boxed;
println!("Unboxed: {}", value);
// Auto-deref for methods
let boxed_str = Box::new(String::from("hello"));
println!("Length: {}", boxed_str.len());
}

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

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