Implementing T::ten()

Viewed 131

I want to implement a function that returns a vector of digits for a given number. For example,

digits(1234) -> Vec[1, 2, 3, 4]

In order to make this function work with any integer type, I wrote the function signature like this:

fn digits<T: Num>digits(T: n) -> Vec<i32> {
   ...
}

The basic idea is to get a last digit by n % 10 in a following loop:

let mut acc: Vec<i32> = Vec::new();
while n != 0 {
  acc.push(n & 10);
  n /= 10;
}
acc.reverse();
acc // return digits

But this works for a specific integer type. I want to make it generic. The problem is that I need a generic 10 as similar to T::one().

I tried multiplying 10 to T::one() but didn't work. One other trick I can think of is to add T::one() ten times:

let ten = T::one() + T::one() + ... + T::one(); // add 10 times

But I am not sure this is the best way to do this? Any ideas?

1 Answers

As Aplet123 mentioned in the comment above, you can use FromPrimitive.

let ten: T = T::from_i8(10).unwrap();

I think unwrap() is safe as we know that it won't fail.

Related