锈:具有拥有和借入价值的结构

问题描述

在Rust中,有什么好的方法struct上拥有一个拥有的字段,然后拥有另一个借用了对另一个字段的引用的字段?借用的字段不需要能够修改原始拥有的字段。

使用两种我能想到的最直接的方法,我会得到不同但相似的错误

注意:请忽略可笑的理论情况和代码中的逻辑错误。这是一个最小的可复制示例的尝试。 更现实的情况是表中的单元格需要按顺序以及行和列进行访问。

使用的基础struct

struct Table<'a> {
    cells: Vec<Cell>,top_cells: Vec<&'a Cell>,}

struct Cell {
    value: String,}

方法1:

impl<'a> Table<'a> {
    pub fn new() -> Self {
        // Cells are a fixed size,set in the constructor
        let cells = Vec::new(); // Todo: Fill cells
        let top_cells: Vec<&'a Cell> = cells.iter().take(3).collect();
        Table { cells,top_cells }
    }
}

错误

error[E0597]: `cells` does not live long enough
error[E0505]: cannot move out of `cells` because it is borrowed

方法2:

impl<'a> Table<'a> {
    pub fn new() -> Self {
        // Cells are a fixed size,set in the constructor
        let cells = Vec::new(); // Todo: Fill cells
        let top_cells = Vec::new();
        
        let mut table = Table { cells,top_cells };
        
        for cell in table.cells.iter().take(3) {
            table.top_cells.push(&cell);
        }
        
        table
    }
}

错误

error[E0515]: cannot return value referencing local data `table.cells`
error[E0505]: cannot move out of `table` because it is borrowed

我试图浏览多个开源库,Rust文章和YouTube视频以寻找灵感,但我开始怀疑这在习惯上是不正确的。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)