Why do try!() and ? not compile when used in a function that doesn't return Option or Result?

后端 未结 4 1346
礼貌的吻别
礼貌的吻别 2020-11-22 06:18

Why does this code not compile?

use std::{fs, path::Path};

fn main() {
    let dir = Path::new(\"../FileSystem\");

    if !dir.is_dir() {
        println!(         


        
4条回答
  •  面向向阳花
    2020-11-22 06:52

    As of Rust 1.26, Rust supports a return value from main(), and thus supports the use of the error-check operator ? (or equivalently the try!() macro) in main() when main() is defined to return a Result:

    extern crate failure;
    use failure::Error;
    use std::fs::File;
    
    type Result = std::result::Result;
    
    fn main() -> Result<()> {
        let mut _file = File::open("foo.txt")?; // does not exist; returns error
        println!("the file is open!");
        Ok(())
    }
    

    The above compiles and returns a file not found error (assuming foo.txt does not exist in the local path).

    Rust playground example

提交回复
热议问题