Skip to content

Instantly share code, notes, and snippets.

@SBeausoleil
Last active March 4, 2021 19:42
Show Gist options
  • Save SBeausoleil/135bb4505f06ba2c745c02522ed25a94 to your computer and use it in GitHub Desktop.
Save SBeausoleil/135bb4505f06ba2c745c02522ed25a94 to your computer and use it in GitHub Desktop.
How to use a Result in Rust
fn read_username_from_file() -> Result<String, io::Error> {
let file: Result<File, io::Error> = File::open("user.txt");
let mut file = match file {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut buffer = String::new();
match file.read_to_string(&mut buffer) {
Ok(_) => Ok(buffer),
Err(e) => Err(e),
}
}
fn main() {
let username = match read_username_from_file() {
Ok(name) => name,
Err(_) => {
println!("Couldn't read username file.");
read_input("Please enter your username:")
}
};
println!("Your username is {}.", username);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment