亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用泛型類型時如何使用整數文字?

使用泛型類型時如何使用整數文字?

慕田峪7331174 2020-02-02 14:23:00
我想實現一個函數,該函數可以計算任何通用類型的整數內的位數。這是我想出的代碼: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。
查看完整描述

2 回答

  • 2 回答
  • 0 關注
  • 730 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號