我想返回向量的一个切片,但编译器抱怨&[Letter]需要明确的生命周期。
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]; } }
我试着增加一个明确的生命周期,但没有成功。
你应该使用 [Letter] 不 &[Letter] 对于 Output 。引用已添加到 index() 方法
[Letter]
&[Letter]
Output
index()
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]; } }