'?'错误传播运算符不起作用

时间:2019-12-16 18:34:15

标签: rust

我想测试?运算符:

fn main() {
    let i = get_result(5)?;
    println!("{}", i);
}

fn get_result(i: i32) -> Result<i32, String> {
    match i {
        i if i > 3 => Ok(i * i),
        _ => Err(String::from("Oops! Don't think so.")),
    }
}

但是,当我尝试对其进行编译时,出现了以下消息:

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
 --> src/main.rs:2:13
  |
2 |     let i = get_result(5)?;
  |             ^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
  |
  = help: the trait `std::ops::Try` is not implemented for `()`
  = note: required by `std::ops::Try::from_error`

很明显,get_result函数返回了Result<i32, String>,但是编译器并不这么认为。我做错了什么?

0 个答案:

没有答案
相关问题