This one has me stumped. I'm trying to write a generic function that takes a vector of integers and converts them to f64 by applying an offset and scaling factor. The integers can be signed or unsigned, of any width, like u8, u16, i32, i64, etc. Something like this:
fn convert_vec<T>(raw: &Vec<T>, offset: f64, scale: f64) -> Vec<f64>
where T: ...
{
let data: Vec<f64> = raw.iter()
.map(|&x| (f64::from(x) + offset) * scale)
.collect();
data
}
I can't figure out how to constrain T to get this (or something equivalent) to compile.
I can't beat the existing solution, but I'll point out that you can place constraints on any type, not just on generics. Here, you have required T: Into<f64> and then you are calling f64::from. From and Into auto-implement each other, but this doesn't happen in generic constraints. You can get your playground link to compile by requiring either of the following:
Ah, funny. I tried that second one in my real code (which is a larger function), hit a lifetime error, and thought it was related to this. Glad to see that it actually works.
But that first one...
f64: From<T> ...
That's awesome! I had no idea you could do that. Thanks, @frsrblch.