Function parameter of different integer types in Rust

Viewed 752

How would I do the following if Rust supported two percent functions?

fn percent(x: u8) -> f32 {
    x as f32 / 100.0
}
fn percent(x: u16) -> f32 {
    x as f32 / 100.0
}

If I try a generic data type like the following:

fn percent<T>(x: T) -> f32 {
    x as f32 / 100.0
}

I get the error

non-primitive cast: T as f32

Can I constrain T with some kind of integer trait?

1 Answers

If you want to only support u8 and u16 type, then:

fn percent<T: Into<f32>>(x: T) -> f32 {
    x.into() / 100.0
}

is enough, since both u8 and u16 can be losslessly converted into a f32. If you want to generically convert, say a u64 to f64, where a loss of precision can occur, you could use ApproxInto trait from conv.

fn percent<T: ApproxInto<f64>>(x: T) -> Result<f64, T::Err> {
    x.approx_into().map(|v| v / 100.0)
}
Related