02猜数字游戏
引入rand库(20221206)
- Cargo.toml增加依赖
rand=0.4.6
- 代码引入包
use rand:Rng
- 产生随机数:
rand::thread_rng().gen_range(low,high)
读取输入
- 引入包
use std::io
- 2.从控制台读取一行文本
1
2
3
let mut line = String.new()//line一定要定义成mut变量,read_line引用调用用
io::stdin().read_line(&mut line)
.expect("读取输入错误!")
string转换成数字
1
2
3
4
5
6
7
8
9
10
11
//方法1
let number:i32=line.trim().parse.expect("Please type a number!")//由于parse是一个泛型输入、返回(Result<F, F::Err>),所以number需声明类型编译器才能推断
//方法2
let number:u32 = match line.trim().parse(){
Ok(n)=>n,
Err(e)=> {
print!("Error msg:{}\n",e);
continue;
}
};
Ordering枚举
- 引入包
use std::cmp::Ordering
- Ordering三个值:
Less、Greater、Equal
Ord trait
- Ord trait定义了
cmp、min、max、eq、ne
等等函数 - 一些数字类型实现了该trait。如:
char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128
match模式匹配
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//1。
match number.cmp(&secret) {
Ordering::Less => print!("太小了!"),
Ordering::Greater => print!("太大了!"),
Ordering::Equal => print!("猜中了!"),
}
//2.
let a_number = Option::Some(10);
match a_number {
Some(x) if x <= 5 => println!("0 to 5 num = {x}"),
Some(x @ 6..=10) => println!("6 to 10 num = {x}"),
None => panic!(),
_ => panic!(),// all other numbers
}
loop循环(20221206)
1
2
3
loop{
//循环体
}
- 脑图
This post is licensed under CC BY 4.0 by the author.