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

问题描述 投票:0回答:1

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

我尝试添加显式生命周期,但没有成功。

rust slice
1个回答
0
投票

您应该使用

[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];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.