Post

Rust里复杂的相互持有或多持有生命周期Arc

遇到一个场景,一个主postbox持有几十张表,每张表可能又相互关联其他表,同时所有的表都被postbox的属性持有,还会被加入到tables里持有,方便释放和清理资源,这样不论如何设置生命周期及持有关系都很麻烦,于是使用ArcWeak进行管理就简单很多

主要目的是一处Arc持有数据,其他地方都是用Weak引用,这样能保持一份数据,跟swift里的关系就很想

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
trait Table{}
struct Postbox {
    tables: Vec<Weak<dyn Table>>,
    table1: Arc<Table1>,
    table2: Arc<Table2>,
}
impl Postbox {
    fn new() -> Self {
    let table1 = Arc::new(Table1{...});
    let table2 = Arc::new(Table2{table1: Arc::downgrade(&table1),...});
    let mut tables: Vec<Weak<dyn Table>> = Vec::new();
    tables.push(Arc::downgrade(&table1) as Weak<dyn Table>);
    tables.push(Arc::downgrade(&table2) as Weak<dyn Table>);

    Postbox{
        ...
        tables: tables,
        table1: table1,
        table2: table2
    }
}
}
struct Table1 {
    ...
}
impl Table for Table1 {

}
struct Table2 {
    table1: Weak<Table1>,
    ...
}
impl Table for Table2 {

}
This post is licensed under CC BY 4.0 by the author.