1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| use std::fs::File;
use std::io;
use std::io::Read;
use std::path::Path;
fn main()
{
let username_or_error = read_username_from_file("hello.txt");
let username = match username_or_error {
Ok(username_) => username_,
Err(e) => {
panic!("There was a problem opening the file: {:?}", e)
},
};
print!("The user name is: {}.", username);
}
fn read_username_from_file<P: AsRef<Path>>(path: P) -> Result<String, io::Error>
{
let file_or_error = File::open(path);
let mut file = match file_or_error {
Ok(file_) => file_,
Err(e) => return Err(e),
};
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => Ok(string),
Err(e) => Err(e),
}
} |
Partager