Is there any technical reason Rust is designed to use dot notation for tuples instead of using index notation (t[2]
)?
let t = (20u32, true, \'b\
I had no part in the design decisions, but here's my perspective:
Tuples contain mixed types. That is, the property type_of(t[i]) == type_of(t[j])
cannot be guaranteed.
However, conventional indexing works on the premise that the i
in t[i]
need not be a compile-time constant, which in turn means that the type of t[i]
needs to be uniform for all possible i
. This is true in all other rust collections that implement indexing. Specifically, rust types are made indexable through implementing the Index trait, defined as below:
pub trait Index where Idx: ?Sized {
type Output: ?Sized;
fn index(&'a self, index: Idx) -> &'a Self::Output;
}
So if you wanted a tuple to implement indexing, what type should Self::Output
be? The only way to pull this off would be to make Self::Output
an enum, which means that element accesses would have to be wrapped around a useless match t[i]
clause (or something similar) on the programmer's side, and you'll be catching type errors at runtime instead of compile-time.
Furthermore, you now have to implement bounds-checking, which is again a runtime error, unless you're clever in your tuple implementation.
You could bypass these issues by requiring that the index by a compile-time constant, but at that point tuple item accesses are pretending to behave like a normal index operation while actually behaving inconsistently with respect to all other rust containers, and there's nothing good about that.