2016-01-21 68 views
5

當編譯如下代碼:f32沒有實施減法?

use std::io::*; 

fn main(){ 
    let reader = stdin(); 
    let nums = reader.lock() 
     .lines().next().unwrap().unwrap() 
     .split_whitespace() 
     .map(|s| s.parse::<i32>().unwrap()) 
     .map(|s| s as f32) 
     .map(|s| (s - 4)/2) 
     .map(|s| s as i32) 
     .collect(); 
} 

我得到一個錯誤說:

性狀core::ops::Sub<_>沒有爲類型f32

這是爲什麼實施?

回答

10

在處理原始類型時,Rust比其他語言更嚴格。大多數數學運算符在兩側都需要相同的類型(除了位移之外,其預期usize作爲右側操作數)。 Rust不會自動將值從一種基本數值類型轉換爲另一種:您必須在代碼中插入明確的轉換。此代碼演示情況:

fn main(){ 
    let a: i32 = 2; 
    let b: i8 = 3; 
    println!("{}", a + b); 
} 

它失敗,出現以下錯誤編譯:

<anon>:4:24: 4:25 error: mismatched types: 
expected `i32`, 
    found `i8` 
(expected i32, 
    found i8) [E0308] 
<anon>:4  println!("{}", a + b); 
           ^
<std macros>:2:25: 2:56 note: in this expansion of format_args! 
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>) 
<anon>:4:5: 4:27 note: in this expansion of println! (defined in <std macros>) 
<anon>:4:24: 4:25 help: see the detailed explanation for E0308 
<anon>:4:20: 4:25 error: the trait `core::ops::Add<i8>` is not implemented for the type `i32` [E0277] 
<anon>:4  println!("{}", a + b); 
          ^~~~~ 
<std macros>:2:25: 2:56 note: in this expansion of format_args! 
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>) 
<anon>:4:5: 4:27 note: in this expansion of println! (defined in <std macros>) 
<anon>:4:20: 4:25 help: see the detailed explanation for E0277 

你的情況是類似的,但它有你混合整數和浮點數的特殊性。在Rust中,整型和浮點型文本被分配一個基於上下文的類型。這就是爲什麼我可以設置a2b3以上:2並不總是一個i32,但如果上下文需要它隱式鍵入i32

就你而言,你試圖從f32減去一個整數。錯誤消息提到Sub<_>; _表示編譯器無法弄清的4文字的類型。

解決方法是使用浮動文字而不是整數常量:

use std::io::*; 

fn main(){ 
    let reader = stdin(); 
    let nums = reader.lock() 
     .lines().next().unwrap().unwrap() 
     .split_whitespace() 
     .map(|s| s.parse::<i32>().unwrap()) 
     .map(|s| s as f32) 
     .map(|s| (s - 4.0)/2.0) 
     .map(|s| s as i32) 
     .collect::<Vec<_>>(); 
}