代码之家  ›  专栏  ›  技术社区  ›  Juan Leni

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

  •  0
  • Juan Leni  · 技术社区  · 6 年前

    我试图在一个非常小的程序中重现这个问题(你可以在这里找到它) 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> . 怎么回事?

    1 回复  |  直到 6 年前
        1
  •  16
  •   Matthieu M.    6 年前

    无法使用 ? 返回的函数中的运算符 ()

    是关于 表达式出现的函数 ? 已应用

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

    因此,编译器抱怨您不能使用 ? 在里面 主要的 因为 .


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

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

    ? 在里面 主要的 .