[英]Why can't rust infer types specified after arithmetic operators?
Can anyone tell me why code 1 works but code2 doesn't?谁能告诉我为什么代码 1 有效,但代码 2 无效?
let guess: u32 = match guess.trim().parse() {
Ok(num) => {num},
Err(e) => {println!("{}",e);0},
};
let guess: u32 = match guess.trim().parse() {
Ok(num) => {num * 2},
Err(e) => {println!("{}",e);0},
};
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.