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

Cell Types

Interior mutability without runtime borrow checking

use std::cell::Cell;
fn main() {
// Cell - for Copy types
let cell = Cell::new(42);
println!("=== Cell ===");
println!("Initial: {}", cell.get());
// Set value
cell.set(100);
println!("After set: {}", cell.get());
// Replace and get old
let old = cell.replace(200);
println!("Replaced {} with 200", old);
println!("Current: {}", cell.get());
// Swap
let other = Cell::new(999);
cell.swap(&other);
println!("\nAfter swap:");
println!("cell: {}", cell.get());
println!("other: {}", other.get());
// Take - replaces with Default
let taken = cell.take();
println!("\nTaken: {}", taken);
println!("After take: {}", cell.get());
// In struct (common pattern)
struct Counter {
count: Cell<i32>,
}
let counter = Counter { count: Cell::new(0) };
counter.count.set(counter.count.get() + 1);
counter.count.set(counter.count.get() + 1);
println!("\nCounter: {}", counter.count.get());
}

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

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