元组
元组是 Rust 中一个最简单的数据结构,它可以存储多个不同类型数据。
元组比数组高级一点,它可以将不同类型的数据以类似数组的方式组合在一起。
数组 vs 元组
数组 ↓
rust
let arr: [i32; 3] = [1, 2, 3]; // ✅ 合法
let invalid = [1, "two", 3]; // ❌ 编译错误(类型不一致)元组 ↓
rust
let tup: (i32, f64, String) = (42, 3.14, "hello".to_string());区别:
- 元组可以包含任意类型的数据,而数组中的每个元素必须是相同类型。
- 元组的元素可能分布在栈上(如果包含堆分配类型如 String,则部分在堆);数组整体都分配在栈上(除非自行使用 Box 封装到堆)。
元组解构
rust
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {}", y);
println!("The value of z is: {}", z);
println!("The value of x is: {}", x);
println!("The value of tup is: {:?}", tup);运行结果: The value of y is: 6.4 The value of z is: 1 The value of x is: 500 The value of tup is: (500, 6.4, 1)
元组中的元素可以单独提取出来,也可以使用元组解构(模式匹配)来同时提取多个元素。