title: How do I form a slice from a HashSet?
body: <p>A struct is defined as:</p>
  
  <pre><code>struct Node {
      set: HashSet&lt;usize&gt;,
      // other fields omitted
  }
  </code></pre>
  
  <p>I <strong>have to</strong> implement a function for a trait (compatibility issues) which needs to return all elements in the set as a slice.</p>
  
  <p>I am aware of something like the following function won't work:</p>
  
  <pre><code>impl Node {
      pub fn set_slice(&amp;self) -&gt; &amp;[usize] {
          let elems: Vec&lt;_&gt; = self.set.iter().cloned().collect();
          &amp;elems[..]
      }
  }
  </code></pre>
  
  <p>The problem is:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0597]: `elems` does not live long enough
    --&gt; src/main.rs:11:10
     |
  11 |         &amp;elems[..]
     |          ^^^^^ borrowed value does not live long enough
  12 |     }
     |     - borrowed value only lives until here
     |
  note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 9:5...
    --&gt; src/main.rs:9:5
     |
  9  | /     pub fn set_slice(&amp;self) -&gt; &amp;[usize] {
  10 | |         let elems: Vec&lt;_&gt; = self.set.iter().cloned().collect();
  11 | |         &amp;elems[..]
  12 | |     }
     | |_____^
  </code></pre>
  
  <p>I know this requirement may sound strange. Despite why I have to do this, is there any 'good' way to achieve this?</p>
  
  <p>If it is possible, I want keep the <code>HashSet</code> container for a O(1) lookup, and I don't want to introduce new struct members in order to save memory. </p>