奇怪的错误:不能在返回`()`[duplicate]的函数中使用`?`运算符

问题描述 投票:0回答:1

我试图在一个非常小的程序中重现问题(你可以在这里找到它Rust REPL

#[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>。到底是怎么回事?

rust
1个回答
4
投票

你误解了运营商正在谈论的功能:

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

是关于表达式出现的函数而不是应用?的表达式:

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

因此,编译器抱怨你不能在?中使用main,因为main的返回类型是()


如果切换到夜间频道,可以使用-> Result<(), Error>作为main的返回类型:

fn main() -> Result<(), Error> {
    let tmp = Bar::version()?;
    Ok(())
}

但是,在稳定的情况下,这还没有(截至1.28),所以你不能在?中使用main

© www.soinside.com 2019 - 2024. All rights reserved.