-
-
Save spdrman/b57e30482fe52da987053a9d7e22bec0 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains 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
/* | |
Exercise about the Rust error handling. | |
Follow the instructions in the comments "Exercise" below. | |
References: | |
Book: https://doc.rust-lang.org/nightly/book/ch09-00-error-handling.html | |
Rust Standard Library: https://doc.rust-lang.org/stable/std/index.html | |
Crates IO: https://crates.io/ | |
random: https://rust-random.github.io/rand/rand/fn.random.html | |
*/ | |
extern crate rand; | |
use rand::Rng; | |
use std::cmp::Ordering; | |
use std::fmt; | |
fn check_input(number: u32) -> Result<u32, AppError> { | |
if number < 1 || number > 10 { | |
panic!("Guess value must be between 1 and 10, got {}.", number); | |
// Err(AppError) //Exercise 2, activate this line instead of the above | |
} else { | |
Ok(number) | |
} | |
} | |
fn main() { | |
println!("Guess the number!"); | |
let secret_number = rand::thread_rng().gen_range(1, 10); | |
for number in (1..10).rev() { //Exercise 1, set number to 12 | |
let input_number = check_input(number); | |
let guess: u32 = match input_number { | |
Ok(number) => number, | |
Err(e) => panic!("Problem with input number: {:?}", e), | |
//Exercise 3, activate this error handling instead of the above | |
// Err(e) => { | |
// eprintln!("{}", e); | |
// continue; | |
// } | |
}; | |
println!("You guessed: {}", guess); | |
match guess.cmp(&secret_number) { | |
Ordering::Less => println!("Too small!"), | |
Ordering::Greater => println!("Too big!"), | |
Ordering::Equal => { | |
println!("-- You win! --"); | |
break; | |
} | |
} | |
} | |
} | |
// Custom error type; can be any type which defined in the current crate | |
// 💡 In here, we use a simple "unit struct" to simplify the example | |
struct AppError; | |
// Implement std::fmt::Display for AppError | |
impl fmt::Display for AppError { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "An Error Occurred, Please Try Again!") // user-facing output | |
} | |
} | |
// Implement std::fmt::Debug for AppError | |
impl fmt::Debug for AppError { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "{{ file: {}, line: {} }}", file!(), line!()) // programmer-facing output | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment