【Rust】结构体 struct
定义结构体
#[derive(Debug)]
struct Rectangle {
name: String,
width: u32,
height: u32,
}
定义结构体方法
impl Rectangle { // 方法 fn area(&self) -> u32 { self.width * self.height } // 更多参数的方法 fn hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } // 关联函数 fn square(size: u32) -> Rectangle { Rectangle { name: String::from(""), width: size, height: size } } }
impl 是 implementation 的缩写。
Self 类型是 impl 块的类型的别名。方法的第一个参数必须有一个名为 self 的 Self 类型的参数。&self 实际上是 self: &Self 的缩写,表示方法借用了 Self 实例。
如果想要在方法中改变调用方法的实例,需要将第一个参数改为 &mut self
更过参数的方法,参数必须放在第二个
关联函数(associated functions),定义不以 self 为第一参数的关联函数(因此不是方法),因为它们并不作用于一个结构体的实例。
结构体使用
let rectangle = Rectangle { name: String::from("R"), width: 10, height: 20 }; println!("{:?}", rectangle); println!("The area of the rectangle {} is {}", rectangle.name, rectangle.area());
字段初始化简写语法(field init shorthand)
let rectangle1 = build_rectangle(String::from("R1"), 10, 20);
println!("{:?}", rectangle1);
println!("The area of the rectangle {} is {}", rectangle1.name, rectangle1.area());
fn build_rectangle(name: String, width: u32, h: u32) -> Rectangle {
Rectangle {name,width,height:h}
}
参数与结构体字段同名时,仅写一个名称就可以,不用写成 key: value 形式。
结构体更新语法(struct update syntax)
let rectangle2 = Rectangle {name: String::from("R2"),..rectangle1};
println!("{:?}", rectangle2);
println!("The area of the rectangle {} is {}", rectangle2.name, rectangle2.area());
.. 语法指定了剩余未显式设置值的字段应与给定实例对应字段相同的值
元组结构体(tuple structs)
struct Color(i32, i32, i32); let black = Color(0, 0, 0);
使用没有命名字段的元组结构体来创建不同的类型,元组结构体有着结构体名称提供的含义,但没有具体的字段名,只有字段的类型。
类单元结构体(unit-like structs)
struct AlwaysEqual; let subject = AlwaysEqual;
没有任何字段的类单元结构体
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!