Rust学习笔记 - Guessing Number
Closed this issue · 0 comments
Guessing Number 程序
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
// created a mutable variable that is currently bound to a new, empty instance of a String
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {}", guess);
}
-
Prelude: 翻译为前奏,默认rust会引入一些default包,如果不在默认返回需要显式引入
-
mut
:mutable的意思在变量名前加上mut代表这个变量可以被mutate -
String::new()
:可以理解成是call了String的一个static method -
&
: reference -
链式调用建议换行
-
read_line
返回的是一个io:Result
的变量,可以用expect
函数来处理异常情况,如果不处理,会给相应的warning让你处理。If this instance of
io::Result
is anErr
value,expect
will cause the program to crash and display the message that you passed as an argument toexpect
. If theread_line
method returns anErr
, it would likely be the result of an error coming from the underlying operating system. If this instance ofio::Result
is anOk
value,expect
will take the return value thatOk
is holding and return just that value to you so you can use it. -
println!("You guessed: {}", guess);
可以使用{}
做为占位符,如果有{}
则必传相应参数
拓展Guessing Number
-
使用rand crates去生成随机数
let secret_number = rand::thread_rng().gen_range(1, 101);
-
比较需要将stdin的输入转成int
let guess: u32 = guess.trim().parse().expect("Please type a number!");
:u32
是一种类型的anotation,告知parse函数需要转换成这种格式的数字 -
代码里如果有已经定义过的变量,可以重复申明
let mut guess = String::new(); // ... let guess: i32 = guess.trim().parse().expect("Please type a number!");
This feature is often used in situations in which you want to convert a value from one type to another type
这种行为在Rust内称为Shadowing
-
使用
match
进行数值比较match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), }
-
添加循环,让用户持续输入直到win
-
容错处理 - 如果输入的不是数字,parse成数字会报错,这种可以用match来处理。
let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, };