1

I’m working with a Rust library that uses references to provide access to child objects (the library is zip, but I’ve had this come up in other contexts as well). Its usage pattern is as follows:

  1. Call Foo::new(arg1: A) -> Foo to get a Foo.
  2. Call Foo.member<'a>(&'a self) -> &'a Bar<'a> to get a Bar, and use it.

Now, I want to write a convenience function that takes arg1 and returns Bar, or an object encapsulating Bar (it’s easy to implement and delegate the relevant traits of Bar.

This seems to be a prime use case for the nonexistent 'self lifetime.

Is there a good, safe, Rustic way to do this encapsulation? The best I’ve been able to come up with uses a bit of unsafe: put Foo in a box, leak it, save its pointer (along with the Bar reference) in an encapsulating struct, and implement Drop to re-box and drop Foo.

Michael Ekstrand
  • 28,379
  • 9
  • 61
  • 93

0 Answers0