用智能指针构建树形结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use std::rc::{Rc,Weak};
use std::cell::RefCell;

#[derive(Debug)]
struct Node {
value: i32,
parent: RefCell<Weak<Node>>,
child: RefCell<Vec<Rc<Node>>>,
}

fn main() {
let leaf = Rc::new( Node {
value: 3,
parent: RefCell::new(Weak::new()),
child: RefCell::new(Vec![]),
});

println!("leaf parent = {:?}",leaf.parent.borrow().upgrade());

let branch = Rc::new( Node {
value: 5,
parent: RefCell::new(Weak::new()),
//父节点指向子节点
child: RefCell::new(Vec![Rc::clone(&leaf)]),
});
//子节点指向父节点
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);
println!("leaf parent = {:?}",leaf.parent.borrow().upgrade());

}

strong_count和weak_count的引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use std::rc::{Rc,Weak};
use std::cell::RefCell;

#[derive(Debug)]
struct Node {
value: i32,
parent: RefCell<Weak<Node>>,
children: RefCell<Vec<Rc<Node>>>;
}

fn main() {
let leaf = Rc::new(Node {
value: 3,
parent: RefCell::new(Weak::new());
children:: RefCell::new(Vec![]),
});
println!{
"leaf strong = {},weak = {}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf)
};
//1:strong_count=1,weak_count=0
let branch = Rc::new { Node {
value: 5,
parent: RefCell::new(Weak::new());
children: RefCell::new(vec![Rc::clone(&leaf)]),//此时branch指向了leaf
//leaf的strong是2
}};
println!(
"branch strong = {},weak = {}",//strong_count=1,weak_count=0
Rc::strong_count(&branch),
Rc::weak_count(&branch));
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);
println!(
"branch strong = {},weak = {}",//strong_count=1,weak_count=1
Rc::strong_count(&branch),
Rc::weak_count(&branch));
}
println!(
"leaf strong = {},weak = {}",//leaf strong_count=2,weak_count=0
Rc::strong_count(&leaf),
Rc::weak_count(&leaf)
);
//如果branch离开作用域,leaf的strong为1,weak为0
}