gpt4 book ai didi

enums - 为什么我不能从函数返回显式类型的结果枚举?

转载 作者:行者123 更新时间:2023-11-29 08:22:44 25 4
gpt4 key购买 nike

简单代码如下:

fn main() {
let R1 = TestResult(10, 20);
match R1 {
Ok(value) => println!("{}", value),
Err(error) => println!("{}", error),
}
}

fn TestResult(a1: i32, a2: i32) -> Result<i32, String> {
if a1 > a2 {
//Compile Pass
//Ok(100)

//Compile with error why ?
std::result::Result<i32, std::string::String>::Ok(100)
} else {
Err(String::from("Error Happens!"))
}
}

我得到了错误

error: expected one of `!`, `.`, `::`, `;`, `?`, `{`, `}`, or an operator, found `,`
--> src/main.rs:15:32
|
15 | std::result::Result<i32, std::string::String>::Ok(100)
| ^ expected one of 8 possible tokens here

error[E0423]: expected value, found enum `std::result::Result`
--> src/main.rs:15:9
|
15 | std::result::Result<i32, std::string::String>::Ok(100)
| ^^^^^^^^^^^^^^^^^^^
|
= note: did you mean to use one of the following variants?
- `std::result::Result::Err`
- `std::result::Result::Ok`

error[E0423]: expected value, found builtin type `i32`
--> src/main.rs:15:29
|
15 | std::result::Result<i32, std::string::String>::Ok(100)
| ^^^ not a value

error[E0308]: mismatched types
--> src/main.rs:15:9
|
9 | fn TestResult(a1: i32, a2: i32) -> Result<i32, String> {
| ------------------- expected `std::result::Result<i32, std::string::String>` because of return type
...
15 | std::result::Result<i32, std::string::String>::Ok(100)
| ^^^^^^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found bool
|
= note: expected type `std::result::Result<i32, std::string::String>`
found type `bool`

我正在使用 Rust 1.26.0。

最佳答案

因为这是语法错误。正确的语法在枚举变体上使用turbofish ( ::<> ):

std::result::Result::Ok::<i32, std::string::String>(100)

您也不应该使用显式类型,除非您真的需要它——这不是惯用的。 Rust 变量和函数使用 snake_case .

fn main() {
let r1 = test_result(10, 20);
match r1 {
Ok(value) => println!("{}", value),
Err(error) => println!("{}", error),
}
}

fn test_result(a1: i32, a2: i32) -> Result<i32, String> {
if a1 > a2 {
Ok(100)
} else {
Err(String::from("Error Happens!"))
}
}

关于enums - 为什么我不能从函数返回显式类型的结果枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50436337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com