【问题标题】:Borrowing within a vector of structures在结构向量中借用
【发布时间】:2019-02-08 11:47:02
【问题描述】:

我有一个结构向量,我想用另一个结构中的值更新一个结构。对于我的用例,我更喜欢循环执行。我正在点击借用检查器,但似乎必须有一个简单的解决方案来解决这类问题。

#[derive(Debug)]
struct Column {
    header: String,
    amount: i32,
}

fn main() {
    let mut spreadsheet: Vec<Column> = Vec::new();

    spreadsheet.push(Column {
        header: "Car".to_string(),
        amount: 30300,
    });
    spreadsheet.push(Column {
        header: "House".to_string(),
        amount: 210800,
    });
    spreadsheet.push(Column {
        header: "Total".to_string(),
        amount: 0,
    });

    for column in &mut spreadsheet {
        //mutable borrow here
        if column.header == "Total" {
            column.amount = spreadsheet[0].amount //immutable borrow here
                        + spreadsheet[1].amount;
        } else {
            column.amount -= 300;
        }
    }

    for column in spreadsheet {
        println!("{:?}", column);
    }
}

【问题讨论】:

  • 嗯,不是你所期望的,但这会起作用play.rust-lang.org/…
  • 谢谢你 - 很好的建议 - 我很可能需要使用两个循环/迭代 - 我希望我可以一次完成 -
  • 如果您推迟推送Total 直到您处理完其他项目之后,您可以轻松完成一次迭代;或者,稍微考虑一下,通过保存它的索引/引用并在循环之后进行突变。

标签: rust borrow-checker


【解决方案1】:

您正在尝试设置电子表格矢量元素,同时在其中进行迭代。由于您一直想使用spreadsheet[0].amountspreadsheet[1].amount,您可以将此值克隆到另一个变量中并使用它们,而不是在电子表格中使用它们。

这是工作代码:

#[derive(Debug)]
struct Column {
    header: String,
    amount: i32,
}

fn main() {
    let mut spreadsheet: Vec<Column> = Vec::new();

    spreadsheet.push(Column {
        header: "Car".to_string(),
        amount: 30300,
    });
    spreadsheet.push(Column {
        header: "House".to_string(),
        amount: 210800,
    });
    spreadsheet.push(Column {
        header: "Total".to_string(),
        amount: 0,
    });

    let car_amount = spreadsheet[0].amount;
    let header_amount = spreadsheet[1].amount;

    spreadsheet.iter_mut().for_each(|column| {
        if column.header == "Total" {
            column.amount = car_amount + header_amount;
        } else {
            column.amount -= 300;
        }
    });

    for column in spreadsheet {
        println!("{:?}", column);
    }
}

Playground with using iter()

由于您想在 for 循环而不是迭代器中执行这些操作,您可以将 spreadsheet.iter_mut()... 代码块更改为以下内容:

for column in &mut spreadsheet {
    if column.header == "Total" {
        column.amount = car_amount + header_amount;
    } else {
        column.amount -= 300;
    }
}

Playground with using for loop

【讨论】:

  • @trentcl,哦,是的,我错过了。谢谢..在答案中修复了它。
  • 谢谢 Akiner - 我的“真正”问题要复杂得多,预先提取值不太有吸引力。我希望有一些我可以使用的“技巧”-
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 2015-01-27
  • 1970-01-01
相关资源
最近更新 更多