1

I would like to test the following struct, where Bar and Baz are traits:

struct Foo {
  bar: Box<Bar>,
  baz: Box<Baz>,
}

impl Foo {
  pub fn new(bar: Box<Bar>, baz: Box<Baz>) -> Foo {
    Foo { bar: bar, baz: baz }
  }
}

In my test for Foo, I have structs FakeBar and FakeBaz and I would like to write a setup method which creates the fakes and the Foo, plumbs them together, and returns all of it as a tuple. Conceptually, I would like something of the form:

fn setup_foo() -> (Box<Foo>, &Bar, &Baz) {
  let fake_bar = Box::new(FakeBar);
  let fake_baz = Box::new(FakeBaz);
  let foo = Foo::new(fake_bar, fake_baz);
  return (foo, &fake_bar, &fake_baz);
}

With this setup, the compiler complains that the references in the returned tuples are missing lifetimes.

So the question: is there any way for me to tell the compiler that this setup is ok because the returned Foo owns the bar and baz we are returning references to? Or am I trying to do something fundamentally impossible here?

I realize that there are a few workarounds (like adding methods to Foo which return references to its bar and baz), but I'd rather not add methods exposing the Foo internals if I don't have to. Also, I am curious as to what I'm missing in the situation above.

Arjan
  • 19,957
  • 2
  • 55
  • 48
Dino
  • 1,576
  • 12
  • 12
  • 2
    Short answer: no, you can't do it. This is a duplicate of http://stackoverflow.com/q/32300132/155423, just with different wording. Substitute "tuple" for "struct" in that question/answer to see why. – Shepmaster Oct 24 '15 at 15:41

0 Answers0