1. use std::io;
    2. use rand::Rng;
    3. use std::cmp::Ordering; //库
    4. fn main() {//循环
    5. println!("Guess the number!");
    6. let secret_number = rand::thread_rng().gen_range(1..101);//生成随机数字
    7. loop {
    8. println!("Please input your guess.");
    9. let mut guess = String::new(); // 声明可变量
    10. //标准库引用 读取一行
    11. io::stdin().
    12. read_line(&mut guess).
    13. expect("Failed to read line ");//expect 会导致程序崩溃,并显示当做参数传递给 expect 的信息。
    14. let guess: u32 = guess.trim().parse().expect("Please type a number!");
    15. println!("You guessed: {}", guess);
    16. match guess.cmp(&secret_number) { // match 分支比较
    17. Ordering::Less => println!("Too small!"),
    18. Ordering::Greater => println!("Too big!"),
    19. Ordering::Equal => {
    20. println!("You win!");
    21. break;
    22. }
    23. }
    24. }
    25. }