Skip to content

Commit 4cdd220

Browse files
authored
Rollup merge of #74989 - pubfnbar:impl-array-indexing, r=KodrAus
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` } ```
2 parents f5230fb + c03dfa6 commit 4cdd220

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

library/core/src/array/mod.rs

+25
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use crate::convert::{Infallible, TryFrom};
1212
use crate::fmt;
1313
use crate::hash::{self, Hash};
1414
use crate::marker::Unsize;
15+
use crate::ops::{Index, IndexMut};
1516
use crate::slice::{Iter, IterMut};
1617

1718
mod iter;
@@ -208,6 +209,30 @@ impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
208209
}
209210
}
210211

212+
#[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
213+
impl<T, I, const N: usize> Index<I> for [T; N]
214+
where
215+
[T]: Index<I>,
216+
{
217+
type Output = <[T] as Index<I>>::Output;
218+
219+
#[inline]
220+
fn index(&self, index: I) -> &Self::Output {
221+
Index::index(self as &[T], index)
222+
}
223+
}
224+
225+
#[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
226+
impl<T, I, const N: usize> IndexMut<I> for [T; N]
227+
where
228+
[T]: IndexMut<I>,
229+
{
230+
#[inline]
231+
fn index_mut(&mut self, index: I) -> &mut Self::Output {
232+
IndexMut::index_mut(self as &mut [T], index)
233+
}
234+
}
235+
211236
#[stable(feature = "rust1", since = "1.0.0")]
212237
impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N]
213238
where

0 commit comments

Comments
 (0)