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

标签 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,所以特征IndexIndexMut无法实现:

// !!! 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]。所以没有这样的实现。

关于rust - 为什么 Rust 元组不使用方括号访问里面的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66792715/

相关文章:

json - 使用 BufReader 在 Rust 中读取 JSON 文件时出错:特征绑定(bind)结果:std::io::Read 不满足

rust - 如何模式匹配包含 &mut 枚举的元组并在匹配臂中使用枚举?

function - 从Rust中的函数返回值有哪些不同的方法?

rust - 为什么通过移动捕获Arc会使我的关闭 FnOnce 而不是 Fn

rust - 如何将具体整数转换为通用整数?

rust - 为什么新类型不使用内部类型的特征?

rust - Amethyst 的 Loader 找不到 Assets 文件

rust - 将图像转换为字节,然后写入新文件

rust - 为什么 Cargo 会为同一个注册表创建多个目录?

rust - 可变引用有移动语义吗?