There is an alternate approach that is worth considering in these cases,
rather than looking for a trait that both types A and B implement that you
can pass into to your function, you create a new trait that both support, and use your new trait instead of the function. It usually means a little bit of duplication and boilerplate, but it is nicely extensible later.
trait HasMeanF64 {
fn mean(&self) -> f64;
}
impl HasMeanF64 for &[f64] {
fn mean(&self) -> f64 {
self.iter().sum::<f64>() / self.len() as f64
}
}
impl HasMeanF64 for Vec<f64> {
fn mean(&self) -> f64 {
self.iter().sum::<f64>() / self.len() as f64
}
}
impl HasMeanF64 for VecDeque<f64> {
fn mean(&self) -> f64 {
self.iter().sum::<f64>() / self.len() as f64
}
}
Now instead of writing mean(v)
you can write v.mean()
.
And if you still want your mean(v)
form you can write
fn mean<T: HasMeanF64>(v: &T) -> f64 {
v.mean()
}