Many things are going wrong here:
- As Shepmaster says,
0
and1
cannot be converted to everything implementingInteger
. UseZero::zero
andOne::one
instead. 10
can definitely not be converted to anything implementingInteger
, you need to useNumCast
for thata /= b
is not sugar fora = a / b
but an separate trait thatInteger
does not require.-x
is an unary operation which is not part ofInteger
but requires theNeg
trait (since it only makes sense for signed types).
Here’s an implementation. Note that you need a bound on Neg
, to make sure that it results in the same type as T
extern crate num;
use num::{Integer, NumCast};
use std::ops::Neg;
fn int_length<T>(mut x: T) -> u8
where
T: Integer + Neg<Output = T> + NumCast,
{
if x == T::zero() {
return 1;
}
let mut length = 0;
if x < T::zero() {
length += 1;
x = -x;
}
while x > T::zero() {
x = x / NumCast::from(10).unwrap();
length += 1;
}
length
}
fn main() {
println!("{}", int_length(45));
println!("{}", int_length(-45));
}