I have a struct A in Rust that has 3 fields, a
, b
and c
struct A {
pub a: typeA,
pub b: typeB,
pub c: typeC
};
typeA
, typeB
and typeC
are three different types of structs themselves. typeB
and
typeC
have typeA
as depdendency. Like for example
struct typeB {
pub bb: typeA,
};
struct typeC {
pub cc: typeA,
};
And typeA
is defined below as follows:
struct typeA {
pub aa: String,
};
I can instantiate A
like this:
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()}},
};
As you can see b1
and c1
both depend on a1
here.
My question is, is there a cleaner way to make the field b1
depend on a1
directly at compile time without me having to
declare them separately in each case for b1
and c1
as shown in instance_a
?
The long term goal is to automatically update b1
and c1
as
a1
gets modified. In other words, if I want to decide to
update the value of a1
to this
a1: typeA {aa : "b".to_string()}
then b1
and c1
should automatically get updated.
I have tried approaching this problem in the following manner.
I have deduced typeA
, typeB
and typeC
as cloneable.
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()},
}
}
}
So whenever I want to update whatever is happening within A
,
I just call A::create("hello_world")
. The issue with this is
I am having to clone multiple times which I would like to avoid.