# GuessGame
# 基础
# 声明变量
静态方法使用 ::
let foo = 5; // 不可变
let mut bar = 5; // 可变
let mut guess = String::new();
# 输入
不写expect捕获异常会有警告,&
表示这是一个引用
use std::io;
// ...other code
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
# 安装依赖
在 Cargo.toml
下的 [dependencies]
添加 rand = "0.3.14"
,然后使用 cargo build
# 更新依赖
cargo update
# 引入外部依赖
extern crate rand;
// 自动调用 use rand
# 最终代码
extern crate rand;
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
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;
}
}
}
}
← rust