gpt4 book ai didi

rust - 不能借为不可变的,因为它也被借为可变的

转载 作者:行者123 更新时间:2023-11-29 07:50:19 25 4
gpt4 key购买 nike

我正在使用库中的结构 FooBar,但在客户端代码中出现编译错误。我将代码简化为:

use std::marker::PhantomData;

struct Foo {
some_str: &'static str,
}

struct Bar<'a> {
some_str: &'static str,
marker: PhantomData<&'a Foo>,
}

impl Foo {
fn read_data(&self) {
// add code here
}
fn create_bar<'a>(&'a mut self) -> Bar<'a> {
Bar {
some_str: "test2",
marker: PhantomData,
}
}
}

fn process(_arr: &mut [Bar]) {}

fn main() {
let mut foo = Foo { some_str: "test" };
let mut array: [Bar; 1] = [foo.create_bar()];
process(&mut array);
foo.read_data();
}

( playground )

输出:

error[E0502]: cannot borrow `foo` as immutable because it is also borrowed as mutable
--> src/main.rs:30:5
|
28 | let mut array: [Bar; 1] = [foo.create_bar()];
| --- mutable borrow occurs here
29 | process(&mut array);
30 | foo.read_data();
| ^^^ immutable borrow occurs here
31 | }
| - mutable borrow ends here

控制台输出的错误非常清楚,但我无法解决问题。

最佳答案

您可以通过将 array 变量放置在带有大括号 ({ ... }) 的新范围内来限制它的生命周期:

fn main() {
let mut foo = Foo { some_str: "test" };
{
let mut array: [Bar; 1] = [foo.create_bar()];
process(&mut array);
}
foo.read_data();
}

关于rust - 不能借为不可变的,因为它也被借为可变的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35054404/

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