Generic Vectors

I have some traits and their methods implemented for &[T] but when I call them on &[f64], I get type conflict. T:Into+From<f64> as trait bound does not help either. Which seems to defeat the objective of having generics in the first place. I need all numeric types, and f64 specifically, to be accepted as T. Is there any way around this?

Do I need to implement somehow T:From<f64> explicitly and if so, how and why?

It's not clear to me at all what exactly the problem is that you're facing. Maybe some code example(s) would help illustrate.

1 Like

For example, I get error: expected &[T] found &[f64] in median call

   fn mad(self,median:f64) -> Result<f64> {
        let diffs:Vec<f64> = self.iter().map(|&s| ((f64::from(s)-median).abs())).collect(); 
        Ok(medians::median(diffs.as_slice()))
    }

where the signature of median is:

pub fn median<T>(set:&[T]) -> f64
       where T: Copy+PartialOrd,f64:From<T>

I used to get around this by defining additional:

pub fn medianf64(set:&[f64]) -> f64 

But, as I say, it totally defeats the object of having generics in the first place. There must be some way?

Does this change fix it?

-        Ok(medians::median(diffs.as_slice()))
+        Ok(medians::median::<f64>(diffs.as_slice()))
1 Like

Wow, the turbo-fish! Did not think of that. What a secret! Thank you so much!!!

Yeah, weird one, that's an inference bug. Maybe this one.

1 Like

Must not let these things get us down, eh? :slight_smile:

1 Like