r/rust • u/Koltaia30 • 2d ago
🙋 seeking help & advice Is this bad practice?
I have some type In a Rc<RefCell<T>> that I need to pass around to some objects to use it mutable. But I also want to pass it to be stored and read by some other object so I did this:
struct ReadRef<T> {
inner: Rc<RefCell<T>>,
}
impl<T> ReadRef<T> {
fn new(inner: Rc<RefCell<T>>) -> Self {
Self { inner }
}
fn borrow(&self) -> Ref<'_, T>
self.inner.borrow(
}
}
2
Upvotes
16
u/NotDuckie 2d ago
Depends entirely on what you are actually trying to do
8
u/dwalker109 2d ago
If it is created once on app init then just passing a reference around is the simplest option.
A static is also a reasonable option, via something like LazyLock.
6
u/afdbcreid 2d ago
It's almost a bad practice to use
Rc<RefCell<T>>.If you use it where you should, then "hiding" like that (which does not really hide anything) is a bad practice, yes. For configuration, for example (like you said in the comments) put individual methods to change each field, and it might be better to wrap each field in a
CellorRefCellindividually.2
u/teerre 2d ago
Rc refcell is most likely a bad practice. Not necessarily, but likely. The problem you ask seen to just be a consequence of a bad design
2
u/sogepunk1 2d ago
Would have to see the rest of the code. Wouldn't say by itself it's a bad practice. You're just wrapping the shared data in a way that only allows for reading.
2
u/phazer99 2d ago
If you're only going to read it, there's no need to use
RefCell. First you can mutate it with ownership and after that put it into anRcfor shared reading.0
u/Sea_Mud6698 2d ago
It is probably fine. You may want to hide the implementation detail that it is even an rc and have specific methods to do the borrows behind the scenes. You will also probably need a weak equivalent.