我想返回向量的一部分,但编译器抱怨 &[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()
方法中。
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];
}
}