可变地借用一个结构字段,同时在闭包中借用另一个 [英] Mutably borrow one struct field while borrowing another in a closure

查看:23
本文介绍了可变地借用一个结构字段,同时在闭包中借用另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个字段的结构,我想使用另一个字段(不可变借用)修改一个字段(可变借用),但我从借用检查器收到错误.

I have a struct containing two fields and I want to modify one field (mutable borrow) using another field (immutable borrow), but I get an error from the borrow checker.

例如以下代码:

struct Struct {
    field1: Vec<i32>,
    field2: Vec<i32>,
}

fn main() {
    let mut strct = Struct {
        field1: vec![1, 2, 3],
        field2: vec![2, 3, 4],
    };

    strct.field1.retain(|v| !strct.field2.contains(v));

    println!("{:?}", strct.field1);
}

给出以下错误:

error[E0502]: cannot borrow `strct.field1` as mutable because it is also borrowed as immutable
  --> src/main.rs:12:5
   |
12 |     strct.field1.retain(|v| !strct.field2.contains(v));
   |     ^^^^^^^^^^^^^------^---^^-----^^^^^^^^^^^^^^^^^^^^
   |     |            |      |    |
   |     |            |      |    first borrow occurs due to use of `strct` in closure
   |     |            |      immutable borrow occurs here
   |     |            immutable borrow later used by call
   |     mutable borrow occurs here

在闭包中使用另一个字段更新一个字段的 Rust 方法是什么?

What are the Rust ways of updating one field using another from within a closure?

推荐答案

通常借用检查器可以区分结构的不同字段,但这在闭包 (lambdas) 中不起作用.

Usually the borrow checker can distinguish between the different fields of a structure, but this doesn't work within closures (lambdas).

相反,借用闭包外的第二个字段:

Instead, borrow the second field outside the closure:

let field2 = &strct.field2;
strct.field1.retain(|v| !field2.contains(v));

这篇关于可变地借用一个结构字段,同时在闭包中借用另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆