Skip to content

Exercise 2.4.1.I Generic Index 's LocalStorageVecIndex seems unnecessary? #127

@fubupc

Description

@fubupc

The text says:

You've probably duplicated a lot of code in exercise 2.4.1.F. We can reduce the boilerplate by defining an empty trait:

trait LocalStorageVecIndex {}

First, implement this trait for usize, RangeTo, RangeFrom, and Range.

Next, replace the multiple implementations of Index with a single implementation. In English:

"For each type T, I and constant N of type usize, implement Index for LocalStorageVec<T, N>, where I implements LocalStorageVecIndex and [T] implements Index"

But it seems the trait bound LocalStorageVecIndex on I is unnecessary. Removing it also works, e.g.:

impl<T, I, const N: usize> std::ops::Index<I> for LocalStorageVec<T, N>
where
    [T]: std::ops::Index<I>,
{
    type Output = <[T] as std::ops::Index<I>>::Output;

    fn index(&self, index: I) -> &Self::Output {
        self.as_ref().index(index)
    }
}

or

impl<T, const N: usize, I> std::ops::Index<I> for LocalStorageVec<T, N>
where
    I: std::slice::SliceIndex<[T]>,
{
    type Output = I::Output;

    fn index(&self, index: I) -> &Self::Output {
        self.as_ref().index(index)
    }
}

Both compile and run without error.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions