Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does not Rust tuple use square bracket to access elements inside? [closed]

Tags:

rust

As titled.

In Rust, I need to use period syntax to access the elements inside a tuple like below (the x.0):

fn main() { 
    let x: (i32, f64, u8) = (500, 6.4, 1);
    println!("{}", x.0);
}

My question is why Rust does not support using a square bracket syntax to access the elements inside a tuple like below which should be a more consistent way?

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.
}
like image 506
Jason Yu Avatar asked Mar 11 '26 18:03

Jason Yu


1 Answers

The square bracket indexing syntax in Rust can always be used with a dynamic index. That means that the following code should work:

for i in 0..3 {
    do_something_with(x[i]);
}

Even if the compiler may not know which value i will take, it must know the type of x[i]. For heterogeneous tuple types like (i32, f64, u8) that's impossible. There is no type that is i32, f64 and u8 at the same time, so the traits Index and IndexMut can't be implemented:

// !!! 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]);
    }
}

Theoretically the standard library could provide an implementation for homogeneous tuples (i32, i32, i32) etc. but this is a corner case that can easily be replaced by an array [i32; 3]. So there is no such implementation.

like image 141
cg909 Avatar answered Mar 13 '26 09:03

cg909



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!