title: How can I write a generic function for computing the average without using any crates?
body: <p>I am currently dealing with some calculations that involve different collections of numbers, such as <code>Vec&lt;u16&gt;</code>, <code>Vec&lt;u32&gt;</code>, <code>VecDeque&lt;16&gt;</code>, etc. I need to calculate the average of these collections several times, therefore I would like to wrap this:</p>
  
  <pre><code>let avg = numbers.map(|x| *x as u32).sum::&lt;u32&gt;() as f32 / numbers.len() as f32;
  </code></pre>
  
  <p>Into a function, where <code>numbers</code> may be any collection.</p>
  
  <p>I tried this:</p>
  
  <pre><code>fn average&lt;T&gt;(numbers: &amp;T) -&gt; f32 {
      numbers.map(|x| *x as u32).sum::&lt;u32&gt;() as f32 / numbers.len() as f32
  }
  </code></pre>
  
  <p>But that of course does not work because <code>T</code> does not necessary implement <code>Iterator</code>. So I added (MVCE):</p>
  
  <pre><code>use std::collections::VecDeque;
  
  fn average&lt;T&gt;(numbers: &amp;T) -&gt; f32
  where
      T: std::iter::Iterator,
      u32: std::iter::Sum&lt;&lt;T as std::iter::Iterator&gt;::Item&gt;,
      u16: std::iter::Sum&lt;&lt;T as std::iter::Iterator&gt;::Item&gt;,
  {
      numbers.sum::&lt;u32&gt;() as f32 / numbers.count() as f32
  }
  
  fn main() {
      let mut input = VecDeque::new();
      input.push_back(1);
      input.push_back(2);
      let _avg = average(&amp;input.iter());
  }
  </code></pre>
  
  <p>But I get <em>"the trait <code>std::iter::Sum&lt;&amp;u32&gt;</code> is not implemented for <code>u16</code>"</em>, and I think this would not work anyway since <code>count()</code> would consume the <code>Iterator</code>.</p>
  
  <p>So I decided to just make multiple functions over slices. e.g.:</p>
  
  <pre><code>fn average_u16&lt;T&gt;(numbers: &amp;[u16]) -&gt; f32 {
      numbers.map(|x| *x as u32).sum::&lt;u32&gt;() as f32 / numbers.len() as f32
  }
  </code></pre>
  
  <p>But that is not satisfying either, since a <code>&amp;VecDeque</code> is not a slice.</p>
  
  <p>Can this be achieved somehow without depending on additional crates?</p>