


code . 打开vscode

rust
fn main() {
println!("hello world!")
}












loop{}循环; break跳出循环
rust
// 引入三方库
use rand::Rng;
// 引入标准库中的输入输出
use std::cmp::Ordering;
use std::io;
// main函数 先执行main函数
fn main() {
// 打印的宏方法
// 打印提示信息
println!("Guess the number!");
//0. 生成随机数
let secret_number = rand::thread_rng().gen_range(1, 101);
// println!("secret_number is: {}", secret_number);
println!("please input your guess");
loop {
// 1.新建guess 字符串变量 mut 表示可以修改的变量 是"mutable 可变的" 的简称
let mut guess = String::new();
// 2.读取输入 stdin 标准的输入方法 read_line输入方法中的获取输入的方法 &mut guess 是引用(可能是类似c中的取地址符) expect??目前无法理解
io::stdin().read_line(&mut guess).expect("failed to read");
// 字符转化为数字 trim 去除前后空白字符 parse 转化为某种类型
// 为了代码的健壮性,防止输入非数字是 崩溃 做如下处理
let guess: u32 = match guess.trim().parse() {
Ok(num) => num, //成功返回num
Err(_) => continue, //错误 不崩溃
};
// 打印输入的guess {}是占位符 插入 后面的参数 可以 有多个{}占位符 一次对应 后面的参数
println!("you guessed: {}", guess);
// 3.比较两个数
match guess.cmp(&secret_number) {
Ordering::Less => println!("small"),
Ordering::Greater => println!("large"),
Ordering::Equal => {
println!("you win !");
break;
}
}
}
}




rust
let i = 10;
i = 20;//报错 不能修改
let i = i + 20;//shadow
println!("{}", i);//30

rust
fn main() {
let guess: i32 = "87".parse().expect("not number");
println!("{}", guess);
}
