Last active
March 4, 2021 19:42
-
-
Save SBeausoleil/135bb4505f06ba2c745c02522ed25a94 to your computer and use it in GitHub Desktop.
How to use a Result in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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