1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
use std::io; // prelude
use rand::Rng; // trait 接口
use std::cmp::Ordering; // 枚举类型
fn main() {
println!("猜数游戏"); // 宏
let secret_number = rand::thread_rng().gen_range(1..101); // 包括1,不包括101
loop {
println!("猜测一个数字:");
let mut guess = String::new(); // mut 可变变量
io::stdin().read_line(&mut guess).expect("failed to read line");
// shadow, 使用相同变量名进行覆盖
let guess: u32 = guess.trim().parse().expect("please type a number!"); // 字符串转整数类型
println!("猜测的数字是: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small"),
Ordering::Greater => println!("Too big"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
|