我想实现一个函数,该函数可以计算任何通用类型的整数内的位数。这是我想出的代码:extern crate num;use num::Integer;fn int_length<T: Integer>(mut x: T) -> u8 { if x == 0 { return 1; } let mut length = 0u8; if x < 0 { length += 1; x = -x; } while x > 0 { x /= 10; length += 1; } length}fn main() { println!("{}", int_length(45)); println!("{}", int_length(-45));}这是编译器的输出error[E0308]: mismatched types --> src/main.rs:5:13 |5 | if x == 0 { | ^ expected type parameter, found integral variable | = note: expected type `T` found type `{integer}`error[E0308]: mismatched types --> src/main.rs:10:12 |10 | if x < 0 { | ^ expected type parameter, found integral variable | = note: expected type `T` found type `{integer}`error: cannot apply unary operator `-` to type `T` --> src/main.rs:12:13 |12 | x = -x; | ^^error[E0308]: mismatched types --> src/main.rs:15:15 |15 | while x > 0 { | ^ expected type parameter, found integral variable | = note: expected type `T` found type `{integer}`error[E0368]: binary assignment operation `/=` cannot be applied to type `T` --> src/main.rs:16:9 |16 | x /= 10; | ^ cannot use `/=` on type `T`我知道问题出在我在函数中使用常量,但是我不明白为什么trait规范Integer不能解决这个问题。的文档Integer说,它PartialOrd使用Self(我假设是指Integer)实现,等特征。通过使用还实现Integer特征的整数常量,是否未定义操作,并且编译器是否应该在没有错误的情况下进行编译?我尝试用常量加后缀i32,但错误消息是相同的,替换_为i32。
添加回答
举报
0/150
提交
取消