mirror of
https://github.com/rust-lang/rust.git
synced 2025-05-14 02:49:40 +00:00
![]() Implement `Index` and `IndexMut` for arrays Adds implementations of `Index` and `IndexMut` for arrays that simply forward to the slice indexing implementation in order to fix the following problem: If you implement `Index<MyIndexType>` for an array, you lose all the other indexing functionality that used to be available to the array via its implicit coercion to a slice. An example of what I'm talking about: ```rust use std::ops::Index; pub enum MyIndexType { _0, _1, _2, _3, _4, _5, _6, _7, } impl<T> Index<MyIndexType> for [T; 8] { type Output = T; fn index(&self, index: MyIndexType) -> &T { unsafe { self.get_unchecked(index as usize) } } } fn main() { let array = [11u8; 8]; println!("{:?}", array[MyIndexType::_0]); // OK println!("{:?}", array[0usize]); // error[E0277] // ^^^^^^^^^^^^^ `[u8; 8]` cannot be indexed by `usize` } ``` |
||
---|---|---|
.. | ||
alloc | ||
backtrace@8b8ea53b56 | ||
core | ||
panic_abort | ||
panic_unwind | ||
proc_macro | ||
profiler_builtins | ||
rtstartup | ||
rustc-std-workspace-alloc | ||
rustc-std-workspace-core | ||
rustc-std-workspace-std | ||
std | ||
stdarch@3c3664355e | ||
term | ||
test | ||
unwind |