I wrote a length function for u32
. I could easily copy/paste/edit to other int types, but when I try to use generics I'm getting stuck. Are there concepts I'm misunderstanding?
The passing length function
fn len_int(n: u32) -> u32 { // 0
std::iter::repeat_with({
let mut l = 0;
// can't call pow on ambiguous numeric type
move || match n / 10u32.pow(l) { // 1
0 => 0,
_ => {
l += 1;
1
}
}
})
.take_while(|&x| x != 0)
// count returns usize
.count() as u32 // 2
}
A failing generic length function: I
fn len_int<T>(n: T) -> T
where
T: Copy + Clone,
{
std::iter::repeat_with({
let mut l = 0;
move || match n / 10.pow(l) {
//1
0 => 0,
_ => {
l += 1;
1
}
}
})
.take_while(|&x| x != 0)
.count() at T // 2
}
The compiler tells me I can't
call method pow on ambiguous numeric type {integer}
cannot divide T by type error
Or convert count()
at the end with an as T
, since T is not a primitive type.
playground