简单的代码如下:
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!"))
}
}
Run Code Online (Sandbox Code Playgroud)
我收到了错误
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`
Run Code Online (Sandbox Code Playgroud)
我正在使用Rust 1.26.0.
因为那是语法错误.正确的语法使用枚举变体上的turbofish(::<>
):
std::result::Result::Ok::<i32, std::string::String>(100)
Run Code Online (Sandbox Code Playgroud)
你也不应该使用显式类型,除非你真的需要它 - 它不是惯用的.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!"))
}
}
Run Code Online (Sandbox Code Playgroud)