gpt4 book ai didi

rust - 如何使用构建器模式生成的数据

转载 作者:行者123 更新时间:2023-12-02 01:28:39 24 4
gpt4 key购买 nike

我是 Rust 新手,这基本上是我尝试编写的第一个 Rust 代码。下面是我正在处理的有问题的代码的简化版本,但错误是完全相同的。

struct A {
pub value : i32
}

impl A {
pub fn new() -> Self {
A {value : 0}
}
}

struct B {
vec_a : Vec<A>
}

impl B {
pub fn new() -> Self {
B {
vec_a : Vec::new()
}
}
pub fn create_A(&mut self) -> &mut A {
let a = A::new();
self.vec_a.push(a);
let last_index = self.vec_a.len() - 1;
&mut self.vec_a[last_index]
}
}

fn main() {
let mut b = B::new();
let a1 : &mut A = b.create_A();
let a2 : &mut A = b.create_A();

println!("{}, {}", a1.value, a2.value);
}

代码给出以下编译错误:

error[E0499]: cannot borrow `b` as mutable more than once at a time
--> src/main.rs:32:23
|
31 | let a1 : &mut A = b.create_A();
| ------------ first mutable borrow occurs here
32 | let a2 : &mut A = b.create_A();
| ^^^^^^^^^^^^ second mutable borrow occurs here
33 |
34 | println!("{}, {}", a1.value, a2.value);
| -------- first borrow later used here

在我看来,编译器告诉我使用 a1 并不安全,因为它是从 b 生成的,但还有另一个可变的借用a1之后的b,可能会改变b,从而导致a1中的数据现在无效。我对这个错误的理解正确吗?如果是这样,我如何告诉编译器 a1a2b 完全不同的部分,并稍后使用 a1开可以吗?

Code in Rust Playground

最佳答案

是的,您的理解是正确的。 a1 是从 b 借用的,当 a1 存在时,您无法修改 b

If so, how do I tell the compiler a1 and a2 are completely different part of b and using a1 later on is fine?

这是错误的,您认为这是可能的事实表明了借用检查器的值(value)。即使在 C++ 中,您的代码也将是未定义的行为。

向向量添加元素可能会导致内存重新分配,从而使对该向量中元素的所有引用无效。这是the same in C++ .

因此编译器是正确的:你不能这样做。 self.vec_a.push() 可能会使您的 a1 引用无效。


即使不会发生重新分配,您的代码仍然不健全。

b 中没有任何内容跟踪对向量的引用。因此,如果您可以a1 时访问 b(&mut 引用到 b)存在,您可以获得另一个引用&b.vec_a[0]。然后,您将同时拥有对同一个 A 对象的 &mut& 引用,这是被禁止的/不合理的。


你想实现什么目标?我确信有一种更适合 Rust 的不同编程模式。您现在使用的根本不兼容 Rust。

关于rust - 如何使用构建器模式生成的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73817472/

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