cargo new guessing_game
cd guessing_game
cargo run
// io输入/输出库,io库来自于标准库
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
//println!("Guess the number!");
//rand::thead_rng函数用来提供特定随机数生成器,gen_range方法调用随机数生成器,区间格式采用的是start..end
//let secret_number = rand::thread_rng().gen_range(1..101);
//println!("The secret number is: {}",secret_number);
//println!("Please input your guess.");
/*
let apple = 5; // 不可变
let mut apple = 5;// 可变
变量默认是不可变的,想要变量可变,可以在变量名强添加mut
::语法表明new是string类型的一个关联函数
关联函数是实现一种特定类型的函数
*/
//let mut guess = String::new();
/*
程序开头没使用 use std::io引入io库,也可以通过std::io::stdin来调用函数
read_line()方法,标准输入句柄中获取用户输入
&表示这个参数是一个引用,让代码的多个部分可以访问同一个数据,而无需再内存中多次拷贝
*/
//io::stdin()
//.read_line(&mut guess)
//使用Result类型来处理潜在的错误
//.expect("Failed to read line");
//println!("You guessed: {}",guess);
println!("Guess the number");
let secret_number = rand::thread_rng().gen_range(1..100);
loop{
println!("Please input your guess!");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
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;
}
}
}
}