nested/
nested.rs

1use superstruct::superstruct;
2
3#[superstruct(variants(A, B), variant_attributes(derive(Debug, Clone)))]
4#[derive(Debug, Clone)]
5pub struct Inner {
6    pub both: &'static str,
7    #[superstruct(only(A), partial_getter(copy))]
8    pub only_a: &'static str,
9}
10
11#[superstruct(variants(A, B), variant_attributes(derive(Debug, Clone)))]
12#[derive(Debug, Clone)]
13pub struct Outer {
14    #[superstruct(only(A), partial_getter(rename = "inner_a"))]
15    pub inner: InnerA,
16    #[superstruct(only(B), partial_getter(rename = "inner_b"))]
17    pub inner: InnerB,
18}
19
20impl Outer {
21    pub fn inner(&self) -> InnerRef<'_> {
22        match self {
23            Outer::A(a) => InnerRef::A(&a.inner),
24            Outer::B(b) => InnerRef::B(&b.inner),
25        }
26    }
27
28    pub fn inner_mut(&mut self) -> InnerRefMut<'_> {
29        match self {
30            Outer::A(a) => InnerRefMut::A(&mut a.inner),
31            Outer::B(b) => InnerRefMut::B(&mut b.inner),
32        }
33    }
34}
35
36#[cfg_attr(test, test)]
37fn main() {
38    let inner_a = InnerA {
39        both: "hello",
40        only_a: "world",
41    };
42    let inner_b = InnerB { both: "hello" };
43
44    let mut a = Outer::A(OuterA {
45        inner: inner_a.clone(),
46    });
47    let b = Outer::B(OuterB {
48        inner: inner_b.clone(),
49    });
50
51    assert_eq!(a.inner_a().unwrap().both, b.inner_b().unwrap().both);
52    assert_eq!(a.inner().both(), b.inner().both());
53    assert_eq!(a.inner_a().unwrap().only_a, "world");
54
55    *a.inner_mut().only_a_mut().unwrap() = "moon";
56    assert_eq!(a.inner().only_a().unwrap(), "moon");
57}