Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return slice of a vector in a struct

I want to return a slice of my vector, but the compiler is complaining that &[Letter] needs an explicit lifetime.

struct Board {
    board: Vec<Letter>,
    width: usize,
    height: usize,
}

impl std::ops::Index<usize> for Board {
    type Output = &[Letter];

    fn index(&self, index: usize) -> &Self::Output {
        return &&self.board[index * self.width..(index + 1) * self.width];
    }
}

I have tried to add an explicit lifetime but it didn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should use [Letter], not &[Letter], for Output. The reference is already added in the index() method.

impl std::ops::Index<usize> for Board {
    type Output = [Letter];

    fn index(&self, index: usize) -> &Self::Output {
        return &self.board[index * self.width..(index + 1) * self.width];
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading