f32 未实现减法?

2024-01-11

编译以下代码时:

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

为什么是这样?


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 中,整数和浮点文字根据上下文分配类型。这就是为什么我可以设置a to 2 and b to 3 above: 2并不总是一个i32,但它隐式键入为i32如果上下文需要的话。

在你的例子中,你试图从一个整数中减去一个整数f32。错误消息提到Sub<_>; that _代表的类型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<_>>();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

f32 未实现减法? 的相关文章

随机推荐