Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
fubupc opened this issue Jul 24, 2024 · 0 comments
Open

Comments

@fubupc
Copy link

fubupc commented Jul 24, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant