[Rust]复合类型

02 · 复合类型

复合类型(compound types)把多个值组合成一个值。Rust 原生的复合类型有元组 与数组 ,而由用户自定义的则有结构体(struct)。这一章从基本组合讲到实用设计模式。

本节要解决什么问题

单一类型只能表达一个值。现实数据总有结构:一对坐标、一条记录、一个栅格......复合类型让我们能以结构化的方式组织数据,并为数据(字段)附加行为(方法)。

1. 元组(Tuple)

元组把固定数量、可能不同类型的值组合成一个整体:

rust 复制代码
let tup: (i32, f64, u8) = (500, 6.4, 1);

// 解构赋值
let (x, y, z) = tup;
println!("{x} {y} {z}");

// 或用索引访问
let second = tup.1; // 6.4

元组的特点

  • 长度固定,编译期确定,不能增删。
  • 元素可异类型(区别于数组)。
  • 匿名,靠"位置"而非"名字"区分字段。
  • 空元祖 () 被称为单元类型(unit) ,用作"无返回值/无意义值",是 fn main() 和没有返回值的函数的返回类型。

实用场景

  • 函数返回多个值:fn divmod(a: i32, b: i32) -> (i32, i32)
  • 临时打包一对关联数据,不值得为此定义结构体。

2. 数组(Array)

数组是固定长度、元素同类型的连续内存块:

rust 复制代码
let arr = [1, 2, 3, 4, 5];
let months = ["一月", "二月", "三月"];   // 字符串字面量数组
let zeros = [0; 3];                      // 三个 0:["0";3] 语法 = [0,0,0]

let first = arr[0];   // 下标访问
let second = arr[1];

数组的关键约束

  • 长度固定(在栈上分配),编译期确定。
  • 越界访问触发 panic:
rust 复制代码
let a = [1, 2, 3];
// let bad = a[5]; // 运行期 panic:index out of bounds

易错点 :不是所有越界都在编译期被发现------a[i] 中 i 是变量时,编译器无法静态得知其值,会在运行时检查并 panic。Rust 不会像 C 那样静默读越界内存。

3. 切片(Slice)

切片是数组或向量的一段连续视图,没有所有权,本质是"指针 + 长度":

rust 复制代码
let s = String::from("hello world");
let hello = &s[0..5];   // "hello" ------ 字符串切片
let world = &s[6..11];  // "world"

let arr = [1, 2, 3, 4, 5];
let part = &arr[1..4];  // [2, 3, 4] ------ 数组切片
  • 切片类型写作 &[T](整段),或用范围 &arr[a..b]。
  • &str 是字符串切片;String 是拥有所有权的字符串。
  • 切片借用底层数据,编译期强制其生命周期合法。

为何 &str 比 String 更适合参数

rust 复制代码
fn takes_slice(s: &str) {}
takes_slice(&String::from("hi")); // &String 自动 deref 成 &str
takes_slice("literal");           // 字面量本身就是 &str

这里的自动转换叫 deref 强转(deref coercion) :编译器沿 Deref trait 的实现链自动把 &String 降为 &str,是纯编译期语法糖。其机制详见 09 · 智能指针 的 Deref 一节。

用 &str 入参可以同时接受 String 与字符串字面量,更通用。

4. 结构体(Struct)

结构体是 Rust 中最常用的自定义复合类型,有三种形式。

4.1 具名字段结构体(Classic Struct)

rust 复制代码
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

let mut user1 = User {
    email: String::from("someone@example.com"),
    username: String::from("someone"),
    active: true,
    sign_in_count: 1,
};
user1.email = String::from("new@example.com"); // 需 let mut

// 结构体更新语法:复用其他实例的其余字段
let user2 = User {
    email: String::from("another@example.com"),
    ..user1  // 其余字段从 user1 搬过来(email 已被显式覆盖)
};

易错点 :..user1 本质是字段级移动。username、sign_in_count 是 String/数字,active 是 bool。若 user1 之后还用,注意它可能已被部分移动(username 移走了)。Rust 允许部分移动后使用未移动字段,但不能整体使用 user1。

4.2 元组结构体(Tuple Struct)

没有字段名,只有类型,靠位置区分:

rust 复制代码
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);

Color 与 Point 即便内部类型相同,也是不同类型 ------这提供了类型安全(见 newtype 模式)。

4.3 单元结构体(Unit Struct)

没有字段,通常用作"标记类型"(marker),或配合 trait 实现:

rust 复制代码
struct Marker;

4.4 结构体方法(impl)

rust 复制代码
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    // 关联函数(类似静态方法),不接收 self
    fn new(width: u32, height: u32) -> Self {
        Self { width, height }
    }

    // 方法:不可变借用 self
    fn area(&self) -> u32 {
        self.width * self.height
    }

    // 方法:可变借用 self
    fn scale(&mut self, factor: u32) {
        self.width *= factor;
        self.height *= factor;
    }

    // 本身所有权的 self(用得较少)
    fn consume(self, s: &str) -> Self {
        Self { height: s.len() as u32, ..self }
    }
}
  • 关联函数 (associated function):Rectangle::new(...),不带 self,常用作构造函数。
  • 方法 :rect.area(),第一个参数是 self/&self/&mut self。

5. Newtype 模式

只用一个字段的元组结构体,包裹基础类型,赋予其语义与安全:

rust 复制代码
// 摄氏与华氏是不同类型的度数,不能混用
struct Celsius(f64);
struct Fahrenheit(f64);

let c = Celsius(100.0);
let f = Fahrenheit(212.0);
// 若把 f 传给接收 Celsius 的函数,编译错误 ------ 类型安全

用途:

  • 在类型层面区分"水杯"和"温度"等同类基础值的不同含义。
  • 为外部类型(trait 的 orphan 规则限制下)实现本地 trait。
  • 隐藏内部实现细节,控制创建方式。

6. 结构体与泛型

rust 复制代码
struct Point<T> {
    x: T,
    y: T,
}

struct Pair<T, U> {
    first: T,
    second: U,
}
  • Point<T> 两个字段必须同类型;Pair<T, U> 可以混合。

7. 实用设计模式

7.1 Builder 模式(构造器)

当结构体有许多可选字段时,用链式设置方法逐步构建:

rust 复制代码
struct HttpRequestBuilder {
    method: String,
    url: String,
    headers: Vec<(String, String)>,
    body: Option<String>,
}

impl HttpRequestBuilder {
    fn new(method: &str, url: &str) -> Self {
        Self {
            method: method.into(),
            url: url.into(),
            headers: Vec::new(),
            body: None,
        }
    }

    fn header(mut self, k: &str, v: &str) -> Self {
        self.headers.push((k.into(), v.into()));
        self
    }

    fn body(mut self, body: &str) -> Self {
        self.body = Some(body.into());
        self
    }
}

let req = HttpRequestBuilder::new("POST", "https://api.example.com")
    .header("Content-Type", "application/json")
    .body("{"k":"v"}")
    // 返回构建好的结构体(此处略示用法)
    ;

mut self(消费 self 并返回新 Self)实现了链式调用。

7.2 Query Builder

把可选的查询参数用 Option 字段建模,逐步累积:

rust 复制代码
struct QueryBuilder {
    select: Option<String>,
    condition: Option<String>,
}
// .with_select(...).with_condition(...).build()

7.3 用结构体组织形状数据

rust 复制代码
struct Shape2D {
    shape_type: &'static str,
    area: f64,
}
struct Point2D { x: f64, y: f64 }
struct CsvRow { fields: Vec<String> }
struct LabeledValue { label: String, value: i64 }
struct Product { name: String, price: f64, quantity: u32 }

结构体把一组相关字段收拢成语义单元,是数据建模的基础工具。

8. 内存与所有权补充

  • 具名字段结构体默认不实现 Copy ,即使所有字段都是数字。需要时手动 #[derive(Clone)](及 Copy)。
  • 结构体可以包含引用字段,但那会引入生命周期参数 <'_>

易错点与陷阱

  1. 数组与切片混淆 :数组定长([i32;5]),切片是借用视图(&[i32])。
  2. 结构体更新语法误用 :..user1 会把非 Copy 字段移走,注意 user1 的部分失效。
  3. 期望结构体自动可复制 :默认不 Copy/Clone,需 derive。
  4. &mut 结构体方法与按值消费 self 的取舍 :self 会夺取所有权,通常仅少数场景使用。

最佳实践

  • 需要"不同含义的基础值"时用 newtype 提升类型安全。
  • 创建复杂(多可选字段)结构体用 Builder 模式。
  • 参数接收用 切片/&str 而非 String,提高通用性。
  • 元组只用于临时/无名字的数据;有名字更可读,升级为结构体。

要点回顾

  • 元组 :定长、异类型、匿名、按位置访问;() 是单元类型。
  • 数组:定长、同类型、栈上连续;越界会 panic。
  • 切片 :&[T]/&str,借用视图,编译期保证有效。
  • 结构体 :具名字段、元组、单元三种形态;impl 提供方法与关联函数。
  • newtype 与 Builder 是两类高价值的设计模式。
相关推荐
风笙9781 小时前
[Rust] 所有权与引用
rust
Kapaseker6 小时前
最近用 Rust 写工具,我发现这 7 个库是真好用
rust
SomeOtherTime1 天前
第 11 讲(大结局):编译期元编程与零拷贝架构——卫生声明宏(macro_rules!)、过程宏 AST 手术刀与 Serde 零反射序列化的终极合龙
rust
SomeOtherTime1 天前
番外篇(第 12 讲):走向工业界深水区——从物理定律看 Rust 在真实工程中的“降维打击”与“阿喀琉斯之踵”
开发语言·rust
Kapaseker1 天前
Rust 桌面开发到底怎么选?先看这篇文章!
rust
奶油话梅糖1 天前
容器启停 2.5 毫秒:11 天 1,700 Star 的 Kiri,用一个 900 KB 的 PID 1 干掉了 runc 和 dockerd
前端·人工智能·rust
wflynn2 天前
GitHub 今日推荐|kiri:clone3 系统调用直达容器,2.5 毫秒启动无 runc 中间层
docker·rust·kubernetes·开源·github·containers
SomeOtherTime2 天前
第 4 讲:突破静态枷锁——智能指针(Box/Rc/Arc)与内部可变性(Cell/RefCell/UnsafeCell)的内存暗道
rust
SomeOtherTime2 天前
第 9 讲:异步并发与 Pin 的底层解剖——async/await 无栈协程状态机脱糖、自引用死锁的终极救赎与 Future/Waker 驱动模型
rust