title: rust: Define a generic function that will accept a borrow to any iterable of things that implement a certain trait
body: <p>I have a trait and a thing that implements that trait:</p>
  <pre><code>trait HasPosition2D {
      fn x(&amp;self) -&gt; &amp;i32;
      fn y(&amp;self) -&gt; &amp;i32;
      fn x_mut(&amp;mut self) -&gt; &amp;mut i32;
      fn y_mut(&amp;mut self) -&gt; &amp;mut i32;
  }
  
  impl HasPosition2D for (i32,i32) {
      fn x(&amp;self) -&gt; &amp;i32 {&amp;self.0}
      fn y(&amp;self) -&gt; &amp;i32 {&amp;self.1}
      fn x_mut(&amp;mut self) -&gt; &amp;mut i32 {&amp;mut self.0}
      fn y_mut(&amp;mut self) -&gt; &amp;mut i32 {&amp;mut self.1}
  }
  </code></pre>
  <p>I can now define generic functions that accept anything that implements HasPosition2D. e.g</p>
  <pre><code>fn print(p: &amp;impl HasPosition2D) {
      println!(&quot;{} {}&quot;, p.x(), p.y());
  }
  </code></pre>
  <p>I have also defined a function that accepts anything that can be turned into an iterable of HasPosition2D. i.e</p>
  <pre><code>fn print_all(ps: impl IntoIterator&lt;Item=impl HasPosition2D&gt;) {
      for p in ps {
          println!(&quot;{} {}&quot;, p.x(), p.y());
      }
  }
  </code></pre>
  <p>This allows me to swap the container type without having to change the code. e.g</p>
  <pre><code>let ps = vec![(42,42), (42,42)];
  print_all(ps);
  let ps = [(42,42), (42,42)];
  print_all(ps);
  </code></pre>
  <p>However, the above function moves the container, I would instead like to borrow. e.g</p>
  <pre><code>//does not complile
  fn print_all2(ps: &amp;impl IntoIterator&lt;Item=impl HasPosition2D&gt;) {
      for p in ps {
          println!(&quot;{} {}&quot;, p.x(), p.y());
      }
  }
  </code></pre>
  <p>But this gives the error:</p>
  <pre><code>error[E0277]: `&amp;impl IntoIterator&lt;Item = impl HasPosition2D&gt;` is not an iterator
    --&gt; src\main.rs:35:14
     |
  35 |     for p in ps {
     |              ^^ `&amp;impl IntoIterator&lt;Item = impl HasPosition2D&gt;` is not an iterator
     |
     = help: the trait `Iterator` is not implemented for `&amp;impl IntoIterator&lt;Item = impl HasPosition2D&gt;`
     = help: the trait `Iterator` is implemented for `&amp;mut I`
     = note: required because of the requirements on the impl of `IntoIterator` for `&amp;impl IntoIterator&lt;Item = impl HasPosition2D&gt;`
  </code></pre>
  <p>I would also like to define a similar function that accepts a mutable borrow.</p>
  <p>And finally, how could I create a type alias for each of these impl traits? ( using <code>#![feature(type_alias_impl_trait)]</code> and/or <code>#![feature(trait_alias)] </code>)</p>
  <p>e.g, for the non borrowed version:</p>
  <pre><code>type HasPosition2DList = impl IntoIterator&lt;Item=impl HasPosition2D&gt;;
  </code></pre>
  <p>or</p>
  <pre><code>//does not compile
  trait HasPosition2DList = IntoIterator&lt;Item=impl HasPosition2D&gt;;
  </code></pre>
  <p>How do I do this?</p>