ruga_guessing_game/lib.rs
1#![allow(unused)]
2
3use std::num::{IntErrorKind, ParseIntError};
4
5pub struct Guess {
6 pub value: i32, // not pub
7}
8
9impl Guess {
10 /* pub fn new(value: i32) -> Guess {
11 if value < 1 || value > 100 {
12 panic!("Guess value must be between 1 and 100, got {}.", value);
13 }
14 Guess { value }
15 } 不要恐慌,要控制输入值 ↓ */
16
17 pub fn new(s: &str, has_panic: bool) -> Result<Guess, ParseIntError> {
18 match s.trim().parse() {
19 Ok(i) => {
20 if i < 1 || i > 100 {
21 if has_panic {
22 panic!("Guess value must be between 1 and 100, got {}.", i);
23 }
24 println!("Guess value must be between 1 and 100, got {}.", i);
25 // let err: Result<i32, ParseIntError> = "".parse(); // 강제 에러 발생!
26 match "".parse::<i32>() {
27 // Ok(n) => return Ok(Guess { value: 0 }),
28 Err(e) => return Err(e),
29 _ => (),
30 }
31 }
32 Ok(Guess { value: i })
33 }
34 // Err(e) => Err(e),
35 Err(e) => {
36 if has_panic {
37 panic!(
38 "Parse Error : {:?}. Guess value must be between 1 and 100.",
39 e
40 );
41 }
42 match e.kind() {
43 IntErrorKind::Empty => {
44 println!("不允许空白文字,请在输入!");
45 Err(e)
46 }
47 IntErrorKind::InvalidDigit => {
48 println!("不允许整数以外的文字,请再输入!");
49 Err(e)
50 }
51 other_error => {
52 println!("发生未知错误,请在输入!");
53 Err(e)
54 }
55 }
56 }
57 }
58 }
59
60 pub fn value(&self) -> i32 {
61 self.value
62 }
63}