title: How to create a struct with a vector of references?
body: <p>Rust seems like such an optimal language - I should've known fighting the compiler would be the price. I'm trying to create a constructor for a struct, and I'm getting <code>does not live long enough</code> errors.</p>
  
  <p>Distilled to the barest of bones, I have:</p>
  
  <pre><code>fn main() {
      println!("RUST PLEASE");
  }
  
  struct Help&lt;'a&gt; {
      list: Vec&lt;&amp;'a Traits&gt;
  }
  
  impl&lt;'a&gt; Help&lt;'a&gt; {
      fn new() -&gt; Help&lt;'a&gt; {
          Help { list: vec![&amp;Test] }
      }
  }
  
  trait Traits {
      fn mice(&amp;self);
  }
  
  struct Test;
  impl Traits for Test {
      fn mice(&amp;self) { print!("WHY"); }
  }
  </code></pre>
  
  <p>So, I'm doing this because that vector <code>list</code> is supposed to hold a list of trait objects. It (supposedly) holds heterogeneously any class that implements the supplied trait. As I understand it, that means I have to use references so the vector has a real size to work with. And since it's a reference, the lifetime has to be there to ensure they live and die together.</p>
  
  <p>The thing is, I know what's wrong. In <code>new</code>, that <code>Test</code> belongs in the <code>new</code> scope, and I try to pass its reference up and out of the function. If I do that, <code>Test</code> goes out of scope and the reference is bad. So what do I do? How can I get the object to last the lifetime of <code>Help</code>? After all, there's really no one to own it.</p>
  
  <p>Also, if anybody has any tips in general on how to return references out of a function in general, I'd be very happy to hear them.</p>
  
  <p><strong>EDIT</strong> This is not the same as simply passing up ownership of the object; I can't do that because the vector <em>needs</em> a reference instead of an object on the stack. The answer by Simon is probably what I'm looking for - I had forgotten I could box things up like that.</p>