代码之家  ›  专栏  ›  技术社区  ›  hasdrubal

特征实现的Rust生存期注释

  •  0
  • hasdrubal  · 技术社区  · 2 年前

    我正试着通过做一些练习来学习铁锈。我遇到的一个问题是终身注释,在下面的例子中,它适合我:

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

    在第六行中,编译器不允许我将输出定义为 type Output = &[T] 出现以下错误:

    `&` without an explicit lifetime name cannot be used here explicit lifetime name needed here

    我尝试过对GenMatrix本身及其数据成员进行生命注释,并尝试过对ops:Index声明进行生命注释。两者都不起作用。如何解决这个问题?

    0 回复  |  直到 2 年前
        1
  •  1
  •   Finomnis    2 年前

    你的错误是你应该使用 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 参数,这就是您想要的。

    推荐文章