我想實現(xiàn)一個函數(shù),該函數(shù)可以計算任何通用類型的整數(shù)內(nèi)的位數(shù)。這是我想出的代碼: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`我知道問題出在我在函數(shù)中使用常量,但是我不明白為什么trait規(guī)范Integer不能解決這個問題。的文檔Integer說,它PartialOrd使用Self(我假設(shè)是指Integer)實現(xiàn),等特征。通過使用還實現(xiàn)Integer特征的整數(shù)常量,是否未定義操作,并且編譯器是否應(yīng)該在沒有錯誤的情況下進行編譯?我嘗試用常量加后綴i32,但錯誤消息是相同的,替換_為i32。
使用泛型類型時如何使用整數(shù)文字?
慕田峪7331174
2020-02-02 14:23:00