struct and impl in Rust

结构体

在Rust语言中,我们可以使用和C/C++一样的关键字struct去声明一个结构体

结构体声明

假设我们需要声明一个方形解构,可以在Rust中使用以下声明

struct Rectangle {
	width: u32,
	height: u32,
}

初始化一个实例

// 不可变实例
let rect1 = Rectangle {
	width: 30,
	height: 60,
};
// 可变
let mut rect2 = Rectangle {
	width: 30,
	height: 60,
};

访问结构体成员

println!("height: {}, width: {}", rect1.width, rect1.height);

直接打印结构体

我们不能直接使用**println!**这个宏去打印结构体。需要对结构体进行修改,添加注解,如下

#[derive(Debug)]
struct Rectangle {
	width: u32,
	height: u32,
}

println!("rect1: {:#?}", rect1);

方法

方法与函数十分类似:它们都使用fn关键字以及一个名称来声明;它们都可以拥有参数和返回值;另外,它们都包含了一段在调用时执行的代码。方法总是被定义在某个结构体(或者枚举类型、trait对象)并且它们的第一个参数永远都是self,用于指代调用该方法的结构体实例

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

// 调用
rect1.area();

方法也可以传入多个参数,假设我们想实现一个方法去判断一个方形是否能容纳另外一个方形解构,如下

impl Rectangle {
	fn can_hold(&self, other: &Rectangle) {
		self.width > other.width && self.height > other.height
	}
}

// 调用方式
let rect2 = Rectangle {
	width: 300,
	height: 5000,
};

rect1.can_hold(&rect2);

关联函数

除了方法,impl块还允许我们定义不用接收self作为参数的函数。由于这类函数与结构体互相关联,所以它们也被称为关联函数(associated function)。我们将其命名为函数而不是方法,是因为它们不会作用于某个具体的结构体实例,我们之前在Rust中使用的String::from就是关联函数的一种。关联函数常常被用作构造器来返回一个结构体的新实例。

impl Rectangle {
	fn square(size: u32) -> Rectangle {
		Rectangle {width: size, height: size}
	}
}

// 调用
let sq = Rectangle::square(3);

Lofi&Cafe

Blog about tech and life!


2022-09-12