为什么Rust元组不使用方括号来访问里面的元素



按标题。

在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)这样的异构元组类型,这是不可能的。不存在同时为i32f64u8的类型,因此无法实现性状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]替代的角落情况。所以有没有这样的实现。

你的意思是花括号吗?还是方括号?

不管怎样,如果我对你的问题的理解有点准确的话,

fn main() {
let x = [0; 5]; // which creates an array with 5 elements valued 0
println!(“{}”, x[0]); // prints 0
}

涉及访问名为x的数组中的索引0并打印它。而CCD_ 11表示名为CCD_ 12的元组的索引0。

我不确定我们是否意见一致。

也许这可能会让你对你的问题有所了解;为什么;https://doc.rust-lang.org/book/appendix-02-operators.html,查找表B-8:元组。您将看到用于访问元组元素(expr.0expr.1(的非运算符符号

表B-10:方括号中,您将看到expr[expr],作为访问集合中元素的一种方式。

据我所知,他们把";"那样";,";为什么";他们是这样走的,我不知道在哪里能找到他们。

最新更新