讲动人的故事,写懂人的代码
2.5 故事3: 比较答案与点数之和
贾克强:“同学们,我们开始用三种语言来实现故事3吧!”
2.5.1 Rust版故事3
这个故事实在是轻松容易地实现了。赵可菲照着书,一下子就写好了。
@@ -1,4 +1,5 @@
use rand::Rng;
+use std::cmp::Ordering;
use std::io;
fn main() {
@@ -16,5 +17,13 @@ fn main() {
.read_line(&mut guess)
.expect("Failed to read line");
+ let guess: u32 = guess.trim().parse().expect("Please type a number!");
+
println!("You guessed: {guess}");
+
+ match guess.cmp(&sum_of_two_dice) {
+ Ordering::Less => println!("You guessed it wrong on the first try!"),
+ Ordering::Greater => println!("You guessed it wrong on the first try"),
+ Ordering::Equal => println!("You win!"),
+ }
}
赵可菲:“这一行就是从Rust的标准库中引入了Ordering
枚举,主要是用来做比较的哦。“
+use std::cmp::Ordering;
"这一行是把玩家输入的guess
从字符串类型解析成无符号32位整数(u32
),然后把空白字符都去掉。如果改不成功,就会打出"Please type a number!"
的错误信息。"
+ let guess: u32 = guess.trim().parse().expect("Please type a number!");
“这段代码就是比较你猜的数字和两颗骰子上的点数之和。用cmp
方法来比一比,然后返回一个Ordering
枚举。根据比较的结果,会显示不一样的信息:如果你猜的数字比点数之和小,就会显示"You guessed it wrong on the first try!"
。如果你猜的数字比点数之和大,也会显示"You guessed it wrong on the first try!"
。要是你猜对了,就会显示"You win!"
”
+ match guess.cmp(&sum_of_two_dice) {
+ Ordering::Less => println!("You guesse