How to convert it to a generic function?

How to convert it to a generic function? This function works perfectly on integer, yet when I've tried to make it generic so it works on any integer not just i32 I cannot for the life of me make it.

extern crate num;
use num::Integer;

pub fn reverse_regetni<T: Integer + std::fmt::Display + std::str::FromStr>(int: T)->T 
{
    let mut stringed = int.to_string();
    let is_negative = int < T::zero();
    let chars_reversed:String = stringed.chars().skip(if is_negative{1}else{0}).collect();
    let res = chars_reversed.parse::<T>().unwrap();
    if is_negative{res * -1}else{res}
}

You need to ensure that the Err type of T's FromStr implementation implements Debug so that you can unwrap it. You can put that in a where bound:

pub fn reverse_regetni<T>(int: T) -> T
where
    T: Integer + std::fmt::Display + std::str::FromStr,
    <T as std::str::FromStr>::Err: std::fmt::Debug,
{
    // ....
}

You will also need to make sure whatever type T is can be negated. You might want to change it to

if is_negative { res.neg() } else { res }

with a std::ops::Neg<Output = T> bound on T. You could also require T to implement num::Signed and replace the whole thing with

res * int.signum()

Hi and thank you for the reply.
Why is it required that we need to provide:

  • std::fmt::Display + std::str::FromStr,

The thing I don't uderstand is, why is it that the 'Integer' doesn't have them already?

Again, I don't understand it. Doesn't 'Integer' "have it" inbuilt?

No; Integer is for both signed and unsigned integer types. If you need negative numbers, you’ll also need the Signed trait.


They’re unrelated to performing arithmetic, so it makes sense to leave them out of the Integer trait. Otherwise, a user-defined integer type would have to include a string parser to be an Integer.

1 Like

Thanks for the explanation.