2016-01-21 117 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<_>>(); 
}