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.
>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];
}
}