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(
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