RUST学习-strut

rust的类型(结构体)定义是通过strut定义

strut定义

见下面,在使用的时候,需要给所有的成员赋值,有一个简写的更新语法。

在声明struts时候,如果strut可变需要声明为mut,如果strut声明为mut,它所有的成员都是mut的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    //声明一个strut,
let imt_user1=User{
user_name:String::from("lh"),
email:String::from("lh@heyi.com"),
sign_in_account:false,
active:true
};

//struts的更新语法 注意..imt_user1
let mut user2=User{
user_name:String::from("lh2"),
email:String::from("lh2@heyi.com"),
..imt_user1
};

struct User {
user_name:String,
email:String,
sign_in_account:bool,
active:bool,
}

tuple strut

元祖结构体,可以对元祖声明称一个结构体,见下面,使用方法如下,可以通过元祖方式访问下标

1
2
3
4
5
6
7
    let black=Color(0,0,0);
let origin=Point(0,0,0);
println!("black.0 {}",black.0);
println!("origin.2 {}",origin.2);

struct Point(i32,i32,i32);
struct Color(i32,i32,i32);

strut的输出

1
2
3
4
5
6
7
8
#[derive(Debug)] //这里表示该数组可以通过{:?} {:#?}打印
struct Rectangle {
width: u32,
length: u32,
}

println!("{:?}",rect);//要加#[derive(Debug)]
println!("{:#?}",rect);//{:#?}比{:?}更易读

strut的方法和函数

函数的定义,和实现在impl块内,一个strut可以有多个impl块

strut的method:第一个参数为&self,调用方式<strut实例名>.<method的Name>

strut的函数:第一个参数非&self,调用方式<strut的名称>::<func的name>

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
#[derive(Debug)]
struct Rectangle {
width: u32,
length: u32,
}

impl Rectangle {
//关联函数
fn from(width:u32,length:u32)->Rectangle{
return Rectangle{
width,length
}
}

fn square(size:u32)->Rectangle{
return Rectangle{
width: size,
length: size,
}
}
}

impl Rectangle {
fn area(&self)->u32{
return self.width*self.length;
}

fn mut_area(&mut self)->u32{
return self.width*self.length;
}

fn area1(self)->u32{
return self.width*self.length;
}

fn can_hold(&self,other:&Rectangle)->bool{
return self.width>other.width && self.length>other.length;
}
}

注意:strut的方法调用,第一个参数可以是self,&self,&mut self,name在调用的时候自动帮你加上&,&mut 注意如果是rect这时候会触发实例的所有权move

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
let mut rect = Rectangle {
width: 50,
length: 30,
};

println!("method : {}", rect.area());//rect自动加上了 &
println!("method : {}", rect.mut_area());//因为是&mut self,所以rect声明为mut,调用时候自动加上了&mut

impl Rectangle {
fn area(&self)->u32{
return self.width*self.length;
}

fn mut_area(&mut self)->u32{
return self.width*self.length;
}

fn area1(self)->u32{
return self.width*self.length;
}

fn can_hold(&self,other:&Rectangle)->bool{
return self.width>other.width && self.length>other.length;
}
}