我正在尝试从函数返回结果并提取它的返回值。我正在使用i32and a&str并且在语句中收到不匹配类型错误match(不能在匹配中使用两种不同的类型)。我该如何解决?
fn use_result(par: i32)-> Result<i32, &'static str> {
if par == 0 {
Err("some error")
} else {
println!("par is 1");
Ok(par)
}
}
fn main() {
// Result
let res = match use_result(1) {
Ok(v) => v,
Err(e) => e,
};
}
//Do something with res: v or res: e
Run Code Online (Sandbox Code Playgroud)
}
在 Rust 中,每个变量都有一个类型。在您现在的代码中,res是 a&'static str或 an i32,这是不允许的。
您的选择是:
fn main() {
let res: i32 = match use_result(1) {
Ok(v) => v,
Err(e) => return,
};
}
Run Code Online (Sandbox Code Playgroud)
fn main() {
match use_result(1) {
Ok(v) => {
handle_success(v);
},
Err(e) => {
handle_error(e);
},
};
}
Run Code Online (Sandbox Code Playgroud)
枚举允许您以类型安全的方式表达类型是“这些可能的变体之一”:
enum IntOrString {
Int(i32),
String(&'static str),
}
fn main() {
let i_or_s: IntOrString = match use_result(1) {
Ok(v) => IntOrString::Int(v),
Err(e) => IntOrString::String(e),
};
}
Run Code Online (Sandbox Code Playgroud)
但这有点奇怪,因为它Result<i32, &'static str>已经是一个枚举,如果你想用 an 做任何事情,IntOrString你稍后需要match对它进行操作(或者if let对其进行操作(或 an等)。
fn main() {
let res: i32 = match use_result(1) {
Ok(v) => v,
Err(e) => panic!("cannot be zero"),
};
}
Run Code Online (Sandbox Code Playgroud)
这更清楚地表达为use_result(1).unwrap()。这通常不是您想要的,因为它不允许函数的调用者恢复/处理错误。但如果您从 调用此命令main(),则错误不会传播到其他地方,因此unwrapping 通常没问题。
| 归档时间: |
|
| 查看次数: |
8434 次 |
| 最近记录: |