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

如何返回结构中向量的切片

  •  1
  • julien  · 技术社区  · 3 年前

    我想返回向量的一个切片,但编译器抱怨&[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];
        }
    }
    

    我试着增加一个明确的生命周期,但没有成功。

    1 回复  |  直到 3 年前
        1
  •  4
  •   Chayim Friedman    3 年前

    你应该使用 [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];
        }
    }
    
    推荐文章