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

后端 未结 4 1302
礼貌的吻别
礼貌的吻别 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:47

    Veedrac's answer helped me too, although the OP's question is slightly different. While reading the Rust documentation, I saw this snippet:

    use std::fs::File;
    use std::io::prelude::*;
    
    let mut file = File::open("foo.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    assert_eq!(contents, "Hello, world!");
    

    Though in the Rust Book they point out the centrality of the main function, if you run this inside it you'll get a similar error. If you wrap the code inside a function handling the errors the aforementioned snippet works:

    use std::error::Error;
    use std::io::prelude::*;
    use std::fs::File;
    
    fn print_file_content() -> Result> {
        let mut f = File::open("foo.txt")?;
        let mut contents = String::new();
    
        f.read_to_string(&mut contents)?;
    
        println!("The content: {:?}", contents);
    
        Ok("Done".into())
    }
    
    fn main() {
        match print_file_content() {
            Ok(s) => println!("{}", s),
            Err(e) => println!("Error: {}", e.to_string()),
        }
    }
    

    P.S. I'm learning Rust so these snippets are not intended as good Rust coding :)

提交回复
热议问题