rust猜数游戏代码

use std::io;
use rand::Rng;
use std::cmp::Ordering;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1,101);

    loop {
        println!("Please input your guess.");
        // mut不可变改为可变
        //String::可以看作是静态方法

        let mut guess =String::new();

        io::stdin().read_line(&mut guess)
            .expect("Faied to read line");
        //match实现类型switch的功能
        let guess:u32 =match guess.trim().parse(){
            //_ 是一个通配符值
            Ok(num) =>num,
            Err(_)=>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;
                }
        }   
     }   
}

相关推荐