奇怪的错误:无法在返回“()”的函数中使用“?”运算符[重复]

2024-03-27

我尝试在一个非常小的程序中重现该问题(您可以在这里找到它)

#[macro_use]
extern crate quick_error;

quick_error! {
    #[derive(Debug)]
    pub enum Error {
        SomeError{
            description("SomeError")
        }
    }
}


pub struct Version {
    foo: u8,
}

pub struct Bar();

impl Bar {
    pub fn version() -> Result<Version, Error> {
        Ok(Version{foo: 1})
    }
}

fn main() {
    let tmp = Bar::version()?;
}

当尝试编译时,我得到以下信息:

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:27:15
   |
27 |     let tmp = Bar::version()?;
   |               ^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`

然而,版本正在返回Result<Version, Error>。到底是怎么回事?


您误解了操作员正在谈论的功能:

不能使用?返回的函数中的运算符()

是关于表达式出现的函数并不是其上的表达式?被申请;被应用:

  • 表达式出现的函数是main.
  • 的表达式?被应用的是Bar::version()?.

因此,编译器抱怨你不能使用? in main因为返回类型main is ().


您可以使用-> Result<(), Box<dyn Error>>作为返回类型main:

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let tmp = Bar::version()?;
    Ok(())
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

奇怪的错误:无法在返回“()”的函数中使用“?”运算符[重复] 的相关文章

随机推荐