智能指针是Rust内存管理的重要工具。本文详解Box、Rc、Arc和RefCell。 ## Box Box在堆上分配内存,用于递归类型和转移大数据: ```rust enum List { Cons(i32, Box), Nil, } use List::{Cons, Nil}; let list = Cons(1, Box::new(Cons(2, Box::new(Nil)))); ``` ## Rc 引用计数,用于多所有权场景(仅单线程): ```rust use std::rc::Rc; let a = Rc::new(5); let b = Rc::clone(&a); let c = Rc::clone(&a); println!("count = {}", Rc::strong_count(&a)); // 3 ``` ## Arc 原子引用计数,线程安全版本的Rc: ```rust use std::sync::Arc; use std::thread; let data = Arc::new(vec![1, 2, 3]); for _ in 0..3 { let data_clone = Arc::clone(&data); thread::spawn(move || { println!("{:?}", data_clone); }); } ``` ## RefCell 内部可变性,在运行时检查借用规则: ```rust use std::cell::RefCell; let data = RefCell::new(vec![1, 2, 3]); data.borrow_mut().push(4); println!("{:?}", data.borrow()); // [1, 2, 3, 4] ``` ## 组合使用 ```rust use std::rc::Rc; use std::cell::RefCell; #[derive(Debug)] struct Node { value: i32, children: RefCell>>, } let leaf = Rc::new(Node { value: 3, children: RefCell::new(vec![]), }); let branch = Rc::new(Node { value: 5, children: RefCell::new(vec![Rc::clone(&leaf)]), }); ``` 选择智能指针的关键:单线程用Rc+RefCell,多线程用Arc+Mutex。