Lazy Structs
Lazy initialization types
LazyCell (Rust 1.80+)
Section titled “LazyCell (Rust 1.80+)”use std::cell::LazyCell;
fn main() { // LazyCell - single-threaded lazy init let lazy: LazyCell<String> = LazyCell::new(|| { println!("Initializing..."); String::from("Hello, Lazy!") });
println!("Before access"); println!("Value: {}", *lazy); // Initializes here println!("Again: {}", *lazy); // Already initialized
// Not initialized if never accessed let never_used: LazyCell<String> = LazyCell::new(|| { println!("This won't print"); String::new() }); println!("\nnever_used created but not accessed"); drop(never_used);
// In struct struct Config { data: LazyCell<String>, }
let config = Config { data: LazyCell::new(|| { println!("Loading config..."); "config value".to_string() }), };
println!("\nConfig data: {}", *config.data);}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google