Rust 结构体 struct 与 impl
更新时间:2026-09-20。struct 是 Rust 组织数据的主力,配合
impl把数据与行为放一起,但它和面向对象的「类」并不等同。继承/多态的表达方式见 trait 与泛型。
一、三种结构体
rust
// 1) 具名字段(最常见)
struct User {
name: String,
active: bool,
}
// 2) 元组结构体:字段只有位置
struct Color(u8, u8, u8);
struct Inches(i32);
// 3) 单元结构体:无字段,常用于实现 trait 的标记类型
struct Marker;
let u = User { name: String::from("alice"), active: true };
println!("{}", u.name);
let c = Color(255, 0, 0);
let red = c.0;二、impl:方法与关联函数
rust
impl User {
// 关联函数(无 self),常作构造器:User::new(...)
fn new(name: &str) -> Self {
User { name: name.to_string(), active: true }
}
// 方法:&self 只读
fn is_active(&self) -> bool {
self.active
}
// 方法:&mut self 可改字段(调用处变量也必须 mut)
fn deactivate(&mut self) {
self.active = false;
}
// 方法:self 拿走所有权(消费自身,如 into_*)
fn into_name(self) -> String {
self.name
}
}
let mut u = User::new("bob"); // 关联函数用 ::,方法用 .
u.deactivate();| 接收者 | 用途 | 代价 |
|---|---|---|
&self | 只读访问 | 借用,最常用 |
&mut self | 修改自身 | 可变借用,调用处需 mut |
self | 消费自身 | 取得所有权,常用于转换/收尾 |
三、更新语法与解构
rust
let base = User { name: "x".into(), active: true };
let copy = User { name: "y".into(), ..base }; // 其余字段从 base 取
// 注意:..base 会把未能 Copy 的字段 move 过来,base 之后部分字段失效字段是 String 等非 Copy 类型时,..base 会移动所有权;要保留 base 用 #[derive(Clone)] 并显式 ..base.clone()。
四、常用派生宏
rust
#[derive(Debug, Clone, Default)]
struct Point { x: f64, y: f64 }
let p = Point { x: 1.0, ..Default::default() }; // 其余字段取默认值
println!("{:?}", p); // Debug 才能 {:?}
let q = p.clone();Debug:启用{:?}/{:#?}调试打印(自定义展示用Display)。Clone:显式深拷贝.clone();Copy(仅限全字段 Copy 的类型)让赋值按位复制。Default:提供Default::default(),配合结构体更新语法很方便。PartialEq:支持==;Eq/Hash/PartialOrd按需派生。
五、常见坑
- 混淆关联函数与方法:
String::new()、User::new()无 self 用::;实例方法用.,写u.new()是错的。 - 方法里改字段但 self 是
&self:编译报错,需要&mut self且调用处变量声明mut。 - 没派生 Debug 就
{:?}:加上#[derive(Debug)],或手写impl fmt::Display。 ..base悄悄 move:含堆字段时移动后再用 base 报错,要么 clone,要么调整字段顺序。- 指望 struct 继承:Rust 没有结构体继承,复用行为用 trait + 组合,见 trait。
总结
Rust 用具名 struct、元组结构体和单元结构体组织数据,用 impl 定义行为:无 self 的关联函数(常作构造器,以 :: 调用)和 &self 只读、&mut self 修改、self 消费自身三类方法(以 . 调用);常用 derive(Debug/Clone/Default/PartialEq) 获得调试、拷贝、默认值与比较能力;struct 更新语法 ..base 会移动非 Copy 字段、Rust 也没有结构体继承,复用行为应靠 trait 与组合而非类继承。