如题。
在 Rust 中,我需要使用句点语法来访问元组中的元素,如下所示(x.0
):
fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
println!("{}", x.0);
}
我的问题是为什么 Rust 不支持使用方括号语法来访问元组内的元素,如下所示,这应该是一种更一致的方式?
fn main() {
// !!! this snippet of code would not be compiled !!!
let x: (i32, f64, u8) = (500, 6.4, 1);
println!("{}", x[0]); // pay attention to the use of "x[0]" here.
}
Rust 中的方括号索引语法始终可以与动态索引一起使用。这意味着以下代码应该可以工作:
for i in 0..3 {
do_something_with(x[i]);
}
即使编译器可能不知道i
将采用哪个值,它也必须知道x[i]
的类型。对于像 (i32, f64, u8)
这样的异构元组类型,这是不可能的。没有类型同时是i32
、f64
和u8
,所以特征Index和 IndexMut无法实现:
// !!! This will not compile !!!
// If the Rust standard library allowed square-bracket indexing on tuples
// the implementation would look somewhat like this:
impl Index<usize> for (i32, f64, u8) {
type Output = ???; // <-- What type should be returned?
fn index(&self, index: usize) -> &Self::Output {
match index {
0 => &self.0,
1 => &self.1,
2 => &self.2,
_ => panic!(),
}
}
}
fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
for i in 0..3 {
do_something_with(x[i]);
}
}
理论上,标准库可以为同构元组(i32, i32, i32)
等提供实现,但这是一个极端情况,可以很容易地用数组[i32; 替换; 3]
。所以没有这样的实现。