Skip to content

Instantly share code, notes, and snippets.

@DavidKloucek
Last active May 13, 2023 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidKloucek/764ba1cdff97fe9ca676fb65795b9e1c to your computer and use it in GitHub Desktop.
Save DavidKloucek/764ba1cdff97fe9ca676fb65795b9e1c to your computer and use it in GitHub Desktop.
// youtube.com/watch?v=wM6o70NAWUI
fn read_file(fnm: &str) -> Result<String, io::Error> {
let mut s = String::new();
File::open(fnm)?.read_to_string(&mut s)?;
return Ok(s);
}
fn read_file_longer_version(fnm: &str) -> Result<String, io::Error> {
let f = File::open(fnm);
let mut f = match f {
Ok(fl) => fl,
Err(e) => return Err(e)
};
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s.to_string()),
Err(e) => Err(e)
}
}
fn main() {
let filename = "test.txt";
// safe
let res2 = read_file(filename);
match res2 {
Ok(data) => {
println!("Result: {}", data);
},
Err(err) => {
println!("Error: {} ", err);
}
}
// unsafe
let res1 = read_file(filename).unwrap();
println!("Result: {}", res1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment