如题。
在 Rust 中,我需要使用句点语法来访问元组中的元素,如下所示 (the x.0):
fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
println!("{}", x.0);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么 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.
}
Run Code Online (Sandbox Code Playgroud)
Rust 中的方括号索引语法总是可以与动态索引一起使用。这意味着以下代码应该可以工作:
for i in 0..3 {
do_something_with(x[i]);
}
Run Code Online (Sandbox Code Playgroud)
即使编译器可能不知道i将采用哪个值,它也必须知道x[i]. 对于这样的异构元组类型(i32, f64, u8)是不可能的。没有任何类型的i32,f64并u8在同一时间,所以性状指标和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]);
}
}
Run Code Online (Sandbox Code Playgroud)
从理论上讲,标准库可以为同类元组(i32, i32, i32)等提供实现,但这是一个可以轻松替换为数组的极端情况[i32; 3]。所以没有这样的实现。