你的错误是你应该使用
type Output = [T]
,因为
&
引用已添加到函数本身:
use std::ops;
struct GenMatrix<T> {
dim: (usize, usize),
data: Vec<T>,
}
impl<T> ops::Index<usize> for GenMatrix<T> {
type Output = [T];
fn index(&self, row: usize) -> &Self::Output {
return &self.data[row * self.dim.1..(row + 1) * self.dim.1];
}
}
请注意,这是一个简短的版本,用于:
impl<T> ops::Index<usize> for GenMatrix<T> {
type Output = [T];
fn index<'a>(&'a self, row: usize) -> &'a Self::Output {
return &self.data[row * self.dim.1..(row + 1) * self.dim.1];
}
}
意思是,的输出
index
具有与其相同的寿命
self
参数,这就是您想要的。