5 Struct
结构体是一个自定义的数据类型,允许你把一些相关的数据组合打包到一起,组成一个有意义的组。
define
1 | struct User { |
instance
1 | let user1 = User{ |
create from other instance
1 | let user2 = User{ |
Tuple Struct without named fields
1 | struct Color(i32, i32, i32); |
method syntax
method(方法),与function(函数)非常相似,不同之处:
- 必须在struct的上下文中声明
- 第一个参数必须是self
1
2
3
4
5
6
7
8
9
10// annotation
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
associated function 关联函数
functions within impl blocks that don’t take self as a parameter.
调用关联函数时使用::标识符,例如, String::from()
Multiple impl Blocks
struct is allowed to have multiple impl blocks