Unable to read file contents to string - Result does not implement any method in scope named `read_to_string`

前端 未结 2 2131
轻奢々
轻奢々 2020-11-28 15:52

I followed the code to open a file from Rust by Example:

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

fn main() {
    let args: Vec<_> = env::args().collect(         


        
2条回答
  •  星月不相逢
    2020-11-28 16:12

    You can also use "?" as well,

    let mut file = File::open(&path)?;
    

    But in that case, your method should return Result

    like,

    fn read_username_from_file() -> Result {
        let mut f = File::open("hello.txt")?;
        let mut s = String::new();
        f.read_to_string(&mut s)?;
        Ok(s)
    }
    

    If you can not return Result then you have to handle error case using expect (mentioned in the accepted answer) or using following way,

    let file = File::open(&opt_raw.config);

    let file = match file {                                                
        Ok(file) => file,                                                  
        Err(error) => {                                                    
            panic!("Problem opening the file: {:?}", error)                
        },                                                                 
    };                                                                     
    

    For more information, please refer this link

提交回复
热议问题