Rust 一个 RC RefCell 的小例子。
Rc 和 Refcell 并不能违反 Rust 的借用原则,多个只读,一个可写借用。 use std::cell::RefCell; use std::rc::Rc; use core::borrow::BorrowMut; #[derive(Debug)] struct Tree { name: String, nodes: RefCell<Vec<Node>>, } #[derive(Debug)] struct Node { id: String, tree: Rc<Tree>, } fn main() { let tree1 = Tree {name: "tree1".into(), nodes: RefCell::new(vec![])}; let tree1rc = Rc::new(tree1); let node1 = Node {id: "node1".into(), tree: tree1rc.clone()}; let node2 = Node {id: "node2".into(), tree: tree1rc.clone()}; tree1rc.nodes.borrow_mut().push(node1); tree1rc.nodes.borrow_mut().push(node2); println!("tree1: {:#?}", tree1rc