012 Rust 元组
·
元组是用一对小括号 ( ) 包括的一组数据,可以包含不同种类的数据。
元组声明
方式一:元素类型自动推断
let tup = (10, 20.5, "Hello"); // 元素类型自动推断
方式二:明确元素类型
let tup:(i32, f64, &'static str) = (10, 20.5, "Hello"); // 明确元素类型
元组元素访问
1、模式匹配解构
let tup:(i32, f64, &'static str) = (10, 20.5, "Hello");
let (x, y, z) = tup; // 模式匹配解构
println!("x={}, y={}, z={}", x, y, z);
2、点号索引访问(推荐)
let tup:(i32, f64, &'static str) = (10, 20.5, "Hello");
let first = tup.0; // 10(i32)
let second = tup.1; // 20.5(f64)
let third = tup.2; // "hello"(&str)
println!("The first element is: {}-{}-{}", first, second, third);
嵌套元组访问
let nested = (("a", "b"), (1, 2));
println!("First element: {}", nested.0.0); // "a"
println!("Last element: {}", nested.1.1); // 2
关键特性
1. 索引必须是字面量常量
2. 不能使用变量作为索引(编译错误):
let index = 1;
// my_tuple[index] // ❌ 错误:元组不支持变量索引
3. 类型安全
每个位置有固定类型,访问时自动推断:
let mixed = ("text", 100, true);
let s: &str = mixed.0; // 正确
// let n: f64 = mixed.1; // ❌ 类型不匹配 (i32 vs f64)
4. 编译时越界检查
访问不存在的索引会直接报编译错误:
let short = (1,);
// short.1 // ❌ 编译错误:no field `1` on type `({integer},)`
使用场景
函数返回多个值。
fn get_user() -> (&'static str, u8, bool) {
("Alice", 30, true)
}
let (name, age, is_active) = get_user();
更多推荐



所有评论(0)