2

I need to create a stack of pointers with the following constraints:

  • The pointers need to point to the same Trait object (so Box seems like a fit)
  • Those Trait objects may need to be modified (RefCell may need to be used?)
  • Two pointers in the stack may need to point to the same object (Rc seems like a fit)

Right now, the only way I've found to accommodate this is to use a Vec<Rc<RefCell<Box<dyn MyTrait>>>>. Is that the best solution though? It looks like a lot of pointer dereferences needed to access the objects.

1
  • *p conveniently goes through the whole pack of references and returns the trait object itself (as far as I recall) Commented Jun 12, 2021 at 17:43

1 Answer 1

3

I'm not quite sure what you exactly mean with:

The pointers need to point to the same Trait object (so Box seems like a fit)

But if you are interested in storing objects of actually different types, then you need trait-objects and those need to be behind some sort of pointer such as a Box. And a Box is generally a good default (but there are alternatives).

Those Trait objects may need to be modified (RefCell may need to be used?)

Well, actually, that could still be done with a Box.

Two pointers in the stack may need to point to the same object (Rc seems like a fit)

Here, it gets difficult because in Rust sharable and mutable are kind of exclude each other. To be sharable, we need an Rc, which you can think of as a shared box. Then to make it mutable anyway, we can use interior mutability by using a RefCell. So, essentially a Rc<RefCell<_>>, which you can think of as a sharable & mutable Box.

Finally, if you put it all together into a Vec you get: Vec<Rc<RefCell<dyn MyTrait>>> (no Box).

This allows you to have different types in the Vec, having some instances even multiple times in it, and still allowing mutable access to each of them.

Sign up to request clarification or add additional context in comments.

1 Comment

For some reason when I tried RefCell<dyn MyTrait> it didn't work. But trying it now I manage to get the code to compile. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.