gpt4 book ai didi

rust - 借用 self 作为可变的和 self 的成员是不可能的?

转载 作者:行者123 更新时间:2023-12-05 02:00:51 24 4
gpt4 key购买 nike

struct State {
x: i32
}

trait A {
fn a(&mut self, b: &i32);
}

impl A for State {
fn a(&mut self, b: &i32) {

}
}

fn main() {
let mut a = State{x: 0};
a.a(&a.x);
}

错误:

error[E0502]: cannot borrow `a` as mutable because it is also borrowed as immutable
--> src/main.rs:17:5
|
17 | a.a(&a.x);
| ^^-^----^
| | | |
| | | immutable borrow occurs here
| | immutable borrow later used by call
| mutable borrow occurs here

看起来错误是在说借用self,但是我只借了一次self,第二个b应该是借用了一个成员结构

当我借用结构的一个成员时,Rust 会完全借用该结构吗?

我阅读了https://doc.rust-lang.org/nomicon/borrow-splitting.html但它表示可以只借用结构的一个元素,只要它不是切片。

最佳答案

当您调用A::a 方法时,它会借用它实现的整个变量。因此,您不能同时拥有对同一对象(或其内容)的不可变引用。

struct State {
x: i32,
y: i32,
}

trait A {
fn a(&mut self, b: &i32); // borrow a whole `Self` always
}

impl A for State {
fn a(&mut self, b: &i32) {
// consider next code
self.x *= 2 + *b;
// if you provide `b` as `&a.x`, then it becomes unclear what result should be
} // borrow a whole `Self` always
}

fn swap(first: &mut i32, second: &mut i32) {} // borrow only provided `i32`s

fn main() {
let mut a = State{x: 0, y: 0};
// a.a(&a.x); // you can't, as long as `a.a` borrows whole `State`
swap(&mut a.x, &mut a.y); // but you can borrow partially if the parts are separate
}

关于rust - 借用 self 作为可变的和 self 的成员是不可能的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66997539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com