title: What is an idiomatic way to define a function taking an iterator without consuming in Rust?
body: <p>I've been working through the 2020 <a href="https://adventofcode.com/" rel="nofollow noreferrer">Advent of Code</a> in Rust, trying to produce solutions involving fairly generic functions, which could (in theory) be reused elsewhere without having to worry too much about types. For day 2, the problem involves checking each line of a file to make sure that it is a string conforming to some given condition. My current approach is to define a function similar to the following:</p>
  <pre class="lang-rust prettyprint-override"><code>fn filter_lines&lt;'a&gt;(lines: impl IntoIterator&lt;Item = &amp;'a str&gt;) -&gt; Vec&lt;&amp;'a str&gt; {
      lines
          .into_iter()
          .filter(|line| verify_line(line))
          .collect()
  }
  </code></pre>
  <p>Here, <code>verify_line</code> is just some function which takes an <code>&amp;str</code> and produces a boolean depending on whether the line conforms to a certain specification.</p>
  <p>The issue is that this function appears to necessarily consume the iterator. I've tried rewriting it as follows to use a reference to <code>lines</code>, and clone <code>lines</code> before operating on this, but this code won't compile:</p>
  <pre class="lang-rust prettyprint-override"><code>fn filter_lines&lt;'a&gt;(lines: &amp;impl IntoIterator&lt;Item = &amp;'a str&gt;) -&gt; Vec&lt;&amp;'a str&gt; {
      let lines = lines.clone();
      lines
          .into_iter()
          .filter(|line| verify_line(line))
          .collect()
  }
  </code></pre>
  <p>The compiler produces the following error:</p>
  <pre class="lang-none prettyprint-override"><code>error[E0507]: cannot move out of `*lines` which is behind a shared reference
    --&gt; src/main.rs:40:5
     |
  40 |     lines
     |     ^^^^^ move occurs because `*lines` has type `impl IntoIterator&lt;Item = &amp;'a str&gt;`, which does not implement the `Copy` trait
  </code></pre>
  <p>I think I understand why doing this isn't allowed, but I'm not sure how to idiomatically define a function such as <code>filter_lines</code> which won't consume the iterator. So, what would be a better way to implement this <code>filter_lines</code> function such that it can be called as follows?</p>
  <pre class="lang-rust prettyprint-override"><code>let some_str: String = get_file_contents();
  let lines = some_str.lines();
  println!(&quot;Filtered lines: {:?}&quot;, filter_lines(&amp;lines));
  println!(&quot;All lines: {:?}&quot;, lines.collect::&lt;Vec&lt;&amp;str&gt;&gt;());
  </code></pre>