我在 Rust 中有一個結構 A,它有 3 個欄位a,b和c
struct A {
pub a: typeA,
pub b: typeB,
pub c: typeC
};
typeA,typeB并且typeC是三種不同型別的結構本身。typeB并
typeC具有typeA依賴性。比如說
struct typeB {
pub bb: typeA,
};
struct typeC {
pub cc: typeA,
};
并且typeA定義如下:
struct typeA {
pub aa: String,
};
我可以這樣實體化A:
let instance_a = A {
a1 : typeA {aa: "a".to_string()},
b1 : typeB {bb: typeA {aa: "a".to_string()}},
c1 : typeC {cc: typeA {aa: "a".to_string()}},
};
如您所見b1,c1兩者都依賴a1于此。我的問題是,是否有一種更簡潔的方法可以使該欄位在編譯時直接b1
依賴,a1而不必在每種情況下分別為b1和宣告它們,c1
如中所示instance_a?
長期目標是自動更新和
b1修改。換句話說,如果我想決定更新this
的值,
那么應該會自動更新。c1a1a1a1: typeA {aa : "b".to_string()}b1c1
我已嘗試通過以下方式解決此問題。我已經推斷出typeA,typeB并且typeC可以克隆。
impl A {
pub fn create(a: &str) -> Self {
let old_instance = typeA {aa : a.to_string()};
A {
a1: old_instance.clone(),
b1: typeB {bb: old_instance.clone()},
c1: typeC {cc: old_instance.clone()},
}
}
}
因此,每當我想更新 中發生的任何事情A時,我只需呼叫A::create("hello_world"). 這個問題是我不得不多次克隆,我想避免。
uj5u.com熱心網友回復:
由于您希望在修改 a 時自動更新 b 和 c,因此您要么希望保留對 a 的參考,要么希望與 Arc 擁有共同所有權。Arc 是只讀的,所以如果你想修改你需要使用內部可變性的東西。有幾種方法可以做到這一切。這是一個(如果您不需要多執行緒,請將 Arc 替換為 Rc)
use std::cell::RefCell;
use std::sync::Arc;
#[derive(Debug)]
struct A {
pub a: Arc<typeA>,
pub b: typeB,
pub c: typeC
}
#[derive(Debug)]
struct typeB {
pub bb: Arc<typeA>
}
#[derive(Debug)]
struct typeC {
pub cc: Arc<typeA>
}
#[derive(Debug)]
struct typeA {
pub aa: RefCell<String>
}
fn main() {
let mut aa = Arc::new(typeA { aa: RefCell::new(String::from("test1")) });
let instance_a = A {
a : aa.clone(),
b : typeB {bb: aa.clone()},
c : typeC {cc: aa.clone()},
};
println!("{:?}", instance_a);
// modify aa
*aa.aa.borrow_mut() = String::from("test2");
println!("{:?}", instance_a);
}
輸出:
A { a: typeA { aa: RefCell { value: "test1" } }, b: typeB { bb: typeA { aa: RefCell { value: "test1" } } }, c: typeC { cc: typeA { aa: RefCell { value: "test1" } } } }
A { a: typeA { aa: RefCell { value: "test2" } }, b: typeB { bb: typeA { aa: RefCell { value: "test2" } } }, c: typeC { cc: typeA { aa: RefCell { value: "test2" } } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/537507.html
標籤:遗产锈结构
