title: Lifetime trouble when slice filtering
body: <p>I want to optionally filter a slice without changing the type. The following approach fails:</p>
  
  <pre><code>use std::collections::HashSet;
  
  fn main() {
      let include: Option&lt;HashSet&lt;i8&gt;&gt; = Some(HashSet::new());
      let y: &amp;[i8] = &amp;[1, 2, 3];
      let z: &amp;[i8] = match include {
          Some(set) =&gt; {
              let filtered: Vec&lt;i8&gt; = y.iter().filter(|&amp;i| set.contains(i)).map(|&amp;i| i).collect();
              filtered.as_slice()
          },
          None =&gt; y
      };
      println!("{:?}", z);
  }
  </code></pre>
  
  <p>with error</p>
  
  <pre><code>error: `filtered` does not live long enough
    --&gt; &lt;anon&gt;:10:9
     |
  9  |             filtered.as_slice()
     |             -------- borrow occurs here
  10 |         },
     |         ^ `filtered` dropped here while still borrowed
  ...
  14 | }
     | - borrowed value needs to live until here
  </code></pre>
  
  <p>-- <a href="https://play.rust-lang.org/?gist=de54009dec06699adedf03f063d7eb64&amp;version=stable&amp;backtrace=0" rel="nofollow noreferrer">playground</a></p>
  
  <p>I understand that <code>filtered</code> doesn't live long enough because the slice is simply a reference into it. I have tried to copy or clone or otherwise make a static version of the resulting <code>filtered.as_slice()</code>, but nothing compiles.</p>
  
  <p>Declaring <code>filtered</code> outside of the definition of <code>z</code> won't work, because it requires <code>set</code> to do the filtering.</p>
  
  <p>I expect this dance of converting to an iterator, then to a vector, and then to a slice is probably not idiomatic. So I'm interested to know of a better approach.</p>