简体   繁体   English

为什么 rust 不能推断算术运算符后指定的类型?

[英]Why can't rust infer types specified after arithmetic operators?

Can anyone tell me why code 1 works but code2 doesn't?谁能告诉我为什么代码 1 有效,但代码 2 无效?

code 1代码 1

let guess: u32 = match guess.trim().parse() {
            Ok(num) => {num},
            Err(e) => {println!("{}",e);0},
        };

code 2代码 2

let guess: u32 = match guess.trim().parse() {
            Ok(num) => {num * 2},
            Err(e) => {println!("{}",e);0},
        };

error错误

error[E0282]: type annotations needed
  --> src/main.rs:18:16
   |
18 |             Ok(num) => {num * 2},
   |                ^^^ cannot infer type
   |
help: consider specifying the type argument in the method call
   |
17 |         let guess: u32 = match guess.trim().parse::<F>() {
   |                                                  +++++

You could create a ambiguous type easily in this way.您可以通过这种方式轻松创建模棱两可的类型。 The Result of a operator is not unique.运算符的Result不是唯一的。 Consider if this existed somewhere in your code.考虑一下这是否存在于您的代码中。

struct A;

// Allow this struct to be used in Parse
impl FromStr for A {
    ... // implementation of FromStr
}

// Allow this struct to be used in add
impl Add<u32> for A {
    type Output = u32;

    // implementation of Add
}

fn main() {
    let k:u32 = "".parse().unwrap() + 5
}

What variant of parse should be used?应该使用什么parse变体? u32 or A ? u32还是A There is no way to tell, both would be valid.没有办法说,两者都是有效的。 A could be defined in some external crate and thus modify code based on a situation that's hard to control. A可以在一些外部 crate 中定义,从而根据难以控制的情况修改代码。

For this reason, rust can't infer types past operators.出于这个原因,rust 无法推断过去运算符的类型。

You can easily clarify the variant used with the turbofish ( ::<> ) operator:您可以轻松阐明与 turbofish ( ::<> ) 运算符一起使用的变体:

fn main() {
    let k:u32 = "".parse::<u32>().unwrap() + 5
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM