结构体方法-Rust

定义方法

方法具有很强的关联性,方法一般定义在struct、enum、trait的上下文中

impl关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#[derive(Debug)]
struct cfx{
length:u32,
width:u32,
}

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

fn main() {
let cfx1 = cfx{length:30,width:50};

println!("{}",cfx1.area());

}

image-20241209105914352

关联函数

String::from就是关联函数

不把self作为第一个参数

关联函数通常用于构造器

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

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

fn zfx(size:u32)->cfx{
cfx{width:size,
length:size}
}

}

fn main() {
let zfx1 = cfx::zfx(30);

println!("{}",zfx1.area());

}

image-20241209170250010

方法与函数的区别

函数(Function)和方法(Method)都是执行代码的代码块,

定义位置:

函数:可以在模块的任何地方定义,与特定的类型无关。

方法:必须定义在impl块中,与特定的类型相关联。

第一个参数:

函数:不自动接收任何参数。

方法:第一个参数总是self,它代表调用该方法的实例。

调用方式:

函数:可以直接调用,例如 my_function(arg1, arg2)
方法:需要通过实例调用,例如 instance.my_method(arg1, arg2)

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
// 定义一个结构体
struct Rectangle {
width: u32,
height: u32,
}

// 定义一个函数
fn area_of_rectangle(width: u32, height: u32) -> u32 {
width * height
}

// 为 Rectangle 类型实现方法
impl Rectangle {
// 定义一个方法
fn area(&self) -> u32 {
self.width * self.height
}
}

fn main() {
let rect = Rectangle { width: 10, height: 20 };

// 调用函数
let area = area_of_rectangle(10, 20);
println!("Area of rectangle using function: {}", area);

// 调用方法
let area = rect.area();
println!("Area of rectangle using method: {}", area);
}

image-20241209170945275