rustLearn

创建项目

1
cargo new study

入门项目

猜数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use std::cmp::Ordering;
use rand::Rng;

fn main() {
println!("开始猜数字游戏");
// 生成一个随机数字
let rand_num=rand::rng().random_range(1..101);
// println!("num is {}",rand_num);
let mut left=1;
let mut right=100;

loop {
println!("现在的范围是:{}-{}",left,right);
let mut input=String::new();
std::io::stdin().read_line(&mut input).expect("输入出错");

let input:u32=match input.trim().parse(){
Ok(num)=>num,
Err(_)=>{
println!("重新输入值!");
continue
}
};

match input.cmp(&rand_num) {
Ordering::Less => {
println!("{} is less!", input);
left=input;
}
Ordering::Greater =>{
println!("{} is greater!", input);
right=input;
}
_ => {
println!("猜中了!");
break
}
}
}
}


基础语法

函数

1
2
3
4
5
6
7
fn main() {
println!("{}",add(5,6) )
}

fn add(x:i32,y:i32)->i32{
x+y
}

循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fn main() {
let a=[1,2,3,4];
for x in a {
println!("{}",x)
}
let mut index=0;
while index<a.len(){
println!("{}",a[index]);
index+=1;
}
index=0;
loop {
if index==a.len(){
break
}
println!("{}",a[index]);
index+=1;
}
}

所有权

所有权的规则

每个值都有一个变量,这个变量是该值的所有者
每个值同时只能有一个所有者
当所有者超出作用域(scope)时,该值将被删除。

引用和借用

引用的例子:

不可变的引用,就是相当于借用,借用了值

1
2
3
4

fn print_str(s:&String){
println!("{}",s)
}

如果是想要在函数内部改变变量的值,并且在原来函数还有其他操作,那么可以通过传入可变的引用来修改原来 的值

1
2
3
4
5
6
7
8
9
10
11

fn main() {
let mut a=String::from("this is a String");
change_string(&mut a, "now is august");
println!("{}",a);
}

fn change_string(old:&mut String, now:&str){
old.clear();
old.push_str(now);
}

总结:

引入这一套的一个原因,就是用于需要将变量传入其他函数,但是在这个函数之后还有其他地方使用。防止在传入给函数的时候,所有权丢失

一些规则:

  1. 在使用可变引用的时候需要注意,在一个作用域中
  2. 不可以同时拥有一个可辨引用和一个不可变引用

切片

fn first_word(s:&String)->&str
有经验的Rust开发者会采用&str作为参数类型,因为这样就可以同时接收String和&str类型的参数了:
fn first_word(s:&str)->&str
一使用字符串切片,直接调用该函数,使用String,可以创建一个完整的String切片来调用该函数
定义函数时使用字符串切片来代替字符串引用会使我们的AP!更加通用,且不会损失任何功能。

结构体

  1. 创建结构体

    1
    2
    3
    4
    5
    #[derive(Debug)]
    struct User {
    name:String,
    sex:bool,// true-> 男, false-> 女
    }

    #[derive(Debug)] 可以打印这个结构体

    1
    println!("{:#?}",user)
  2. 添加成员函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    use std::fmt::{Display, Formatter};

    #[derive(Debug)]
    struct User {
    name:String,
    sex:bool,// true-> 男, false-> 女
    age:u8,
    }
    //
    // impl Display for User {
    // fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    // write!(f,"{} {}",self.name,if self.sex {"男"} else {"女"})
    // .expect("格式化失败");
    // Ok(())
    //
    // }
    // }

    impl User{

    fn set_name(&mut self,name:&str){
    self.name= name.parse().unwrap();
    }

    fn get_name(&self)->&str{
    &self.name
    }

    fn set_age(&mut self,age:u8){
    self.age=age;
    }

    fn get_age(&self)->u8{
    self.age
    }

    }
    fn main() {
    let mut user=User{
    name:String::from("august"),
    sex:true,
    age:18,
    };
    println!("{:#?}",user);
    println!("user name is {},age is {}",user.get_name(),user.get_age());
    user.set_name("bugust");
    user.set_age(19);
    println!("user name is {},age is {}",user.get_name(),user.get_age());

    }

枚举

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use std::fmt::{Display, Formatter};

enum Shape {
Circle(f64),
Rectangle(f64, f64),
Triangle(f64, f64, f64),
}

impl Display for Shape {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Shape::Circle(radius) => write!(f, "Circle with radius {}", radius),
Shape::Rectangle(width, height) => write!(f, "Rectangle with width {} and height {}", width, height),
Shape::Triangle(a, b, c) => write!(f, "Triangle with sides a={}, b={}, c={}", a, b, c),
}.expect("error");
Ok(())

}
}

impl Shape {
fn calculate_area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(radius) => std::f64::consts::PI * radius * radius,
Shape::Rectangle(width, height) => width * height,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
},
}
}
}


fn main() {
let shape = Shape::Circle(5.0);
println!("shape is {}",shape);
println!("area of shape is {}",Shape::calculate_area(&shape));
}

option 枚举

用于替代的是null

因为在rust 的开发者看来,null 是一个错误

match

利用match 做一个返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
use std::fmt::{Display, Formatter};

struct User {
name:String,
age:i32,
sex:bool
}

impl User{
fn new(name:&str,age:i32,sex:bool)->User{
User{
name:name.to_string(),
age,
sex
}
}

fn get_sex(&self)->&str{
// 利用match 返回性别
match self.sex {
true => "男",
false => "女"
}
// 会将整个表达式的结果返回
// 表达式的结果就是Match 的结果
// 因此可以使用这个方法做返回值
}
}

impl Display for User{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "name: {} age: {} 性别: {}", self.name, self.age, self.get_sex()).expect("发生错误");
Ok(())
}
}


fn main() {
let user = User::new("张三", 18, true);
println!("user is: {}",user.to_string())
}

let some

主要是用于match 的优化,只针对一个匹配

1
2
3
4
5
6
7
8
9
10
fn main() {
let user = User::new("张三", 18, true);
println!("user is: {}",user.to_string())
let num=Some(03);
if let Some(04)=num{
println!("no")
}else{
println!("yes")
}
}

rustLearn
https://tsy244.github.io/2025/07/26/rustLearn/
Author
August Rosenberg
Posted on
July 26, 2025
Licensed under