Self-referential structs and mutability again

I'm still trying to wrap my head around mutability and read-write locks.

Struct Base is needed in OnTopA and OnTopB for convenience in some methods. But this becomes a problem when I need mutability: Arc<Base> is immutable. But if I make it Arc<RwLock<Base>>, it brings a lot of complexity.

I wonder, is there a wrapper that makes it in a convenient way?

struct OnTopA {
    base: Arc<Base>,
    // some own stuff
}

struct OnTopB {
    base: Arc<Base>,
    // some own stuff
}

struct Container {
    a: OnTopA,
    b: OnTopB,
    base: Arc<Base> // this is optional
}

struct MyAxumAppState {
    container: Arc<RwLock<Container>>
}

(As an alternative solution, I found out, I can remove Arc<Base> from both OnTop* structs, and pass a simple immutable ref to them when needed (there are just 3-4 calls like this).

This would be my preferred solution.

If you start having more methods then you could have a temporary struct with a reference to OnTop* and Base and you define the methods on it (so that you can do on_top.with(&mut base).method(args) and you don't have to add a &mut Base argument to all the methods).

Also consider giving this a read After NLL: Interprocedural conflicts · baby steps

4 Likes

These view structs are a great idea! I never met these before. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.