rust - 借用对结构中属性的引用

标签 rust

好像如果你借用了一个struct字段的引用,整个struct都被认为是借用的。我已经设法隔离并举例说明我想做什么。我只想获得对B 中某个字段的“只读”引用以获取一些数据,然后修改B 中的另一个字段。是否有惯用的 Rust 方法可以做到这一点?

struct A {
    i: i32,
}

struct B {
    j: i32,
    a: Box<A>,
}

impl B {
    fn get<'a>(&'a mut self) -> &'a A {
        &*self.a
    }
    fn set(&mut self, j: i32) {
        self.j = j
    }
}

fn foo(a: &A) -> i32 {
    a.i + 1
}

fn main() {
    let a = Box::new(A { i: 47 });
    let mut b = B { a: a, j: 1 };
    let a_ref = b.get();
    b.set(foo(a_ref));
}
error[E0499]: cannot borrow `b` as mutable more than once at a time
  --> src/main.rs:27:5
   |
26 |     let a_ref = b.get();
   |                 - first mutable borrow occurs here
27 |     b.set(foo(a_ref));
   |     ^ second mutable borrow occurs here
28 | }
   | - first borrow ends here

最佳答案

这是语言的一个特性。从编译器的角度来看,当通过 get() 借用 a 时,它无法知道调用 set() 函数是安全的

您的 get() 函数可变地借用了 b,并返回一个引用,因此 b 将保持借用状态,直到该引用超出范围.

你有几种处理方法:

  1. 将您的两个字段分成两个不同的结构

  2. 将需要访问这两个属性的代码移到B

    的方法中
  3. 公开您的属性,这样您就可以直接获取对它们的引用

  4. 在设置之前计算新值,如下所示:

    fn main() {
        let a = Box::new(A { i: 47 });
        let mut b = B { a: a, j: 1 };
        let newval = {
            let a_ref = b.get();
            foo(a_ref)
        };
        b.set(newval);
    }
    

关于rust - 借用对结构中属性的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37038780/

相关文章:

unit-testing - 为编译器阶段编写可维护的测试

rust - 我的类似RefCell的结构上的rowe_mut()不起作用

rust - 改变不可变的局部变量是未定义的行为吗?

rust - 从 rust 向量中间开始的单次循环迭代

rust - 使用 Rc 实现二叉树时,不能将不可变借用内容借用为可变内容

rust - 需要帮助理解迭代器的生命周期

Rust 初始化泛型类型

rust - 与 Rust 借用检查器战斗

struct - 遍历struct Hashmap并将值添加到self的另一部分

rust - 使用 Box 分配大型数组时,线程 '<main>' 已溢出其堆栈