0

EDIT: Not a duplicate. Please read the entire post.

Say I have a struct Foo<T>:

struct Foo<T> {
  data: T
}

which is used by an implementation that works with objects of type Rc<RefCell<Foo<T>>>. I need to return a reference to the data inside of a Foo<T>:

fn get(&self, some_arg) -> &T {
  // ... some code ...
  // foo is of type Rc<RefCell<Foo<T>>>
  &foo.borrow().data  // this doesn't work
}

But the Ref<'b, T> returned by foo.borrow() is only alive for the scope of get(), so the compiler complains. I want to be able to do this:

// bar has the get() method above
let val = bar.get(some_arg);  // bind val to a &T
// do stuff with val

How do I do this?

EDIT: I've already read all other SO posts that could be relevant. This is not a duplicate. The other posts suggested by Shepmaster all have different types (not Rc<RefCell<Foo<T>>>): 1) There is no Rc-wrapped member in Foo. 2) There is not even RefCell usage in the second "duplicate" post.

Tsukki
  • 315
  • 2
  • 8
  • Or [Can't figure out a function to return a reference to a given type stored in RefCell>](http://stackoverflow.com/q/25233925/155423) or [Encapsulation and RefCell](http://stackoverflow.com/questions/29401626/encapsulation-and-refcell). All found via searching for "rust return refcell". – Shepmaster Apr 15 '16 at 13:49
  • Not a duplicate. See edit. – Tsukki Apr 15 '16 at 13:57
  • *There is not even `RefCell` usage* — all three linked posts definitely use `RefCell`, so I'm not sure how this statement arises. The problem you are asking is the same as all three posts - you *cannot* preserve the reference from `borrow` any longer than the value returned from `borrow`; that's the entire point of `RefCell`. Wrapping it in an `Rc` or putting different types inside can not change that. – Shepmaster Apr 15 '16 at 14:06
  • Sorry, but did you even read the answers? The answer to the first post you linked removed all uses of `RefCell`. The answer to the second post clones an `Rc`, which is not part of my `Foo`. The borrow was only used to make the clone. – Tsukki Apr 15 '16 at 14:39
  • 1
    *The answer to the first post you linked removed all uses of `RefCell`.* That's because you just can't return a borrowed pointer to a value owned by `RefCell`; it's not memory-safe. Somebody could clear the contents of the `RefCell` while somebody else still has a pointer to it. A `&T` is supposed to be a pointer to an **immutable** `T`. – Francis Gagné Apr 20 '16 at 03:12

0 Answers0