gpt4 book ai didi

rust - 突变结构内向量中的结构

转载 作者:行者123 更新时间:2023-12-03 11:27:54 24 4
gpt4 key购买 nike

我正在尝试突变一个结构,该结构是另一个结构中向量的成员。尽管阅读了文档和有关所有权的许多许多文章,但我显然仍然缺少一些东西,因为我无法使用以下相对琐碎的代码来工作。
我在add_content(&mut bar);行上遇到编译器错误,该行显示cannot borrow data in a '&' reference as mutable,我知道这是对的,但是我无法弄清楚如何使其工作。
我一直在阅读有关Box<T>Cell<T>RefCell<T>的信息,并且想知道是否可能需要使用其中之一,但我对它们并不熟悉,并且看来下面的琐碎示例应该可以正常工作而不会造成额外的麻烦。

#[derive(Debug)]
struct Foo {
id: u32,
bars: Vec<Bar>,
}

#[derive(Debug)]
struct Bar {
id: u32,
content: String,
}

fn main() {
let mut foos: Vec<Foo> = Vec::new();
foos.push(Foo {
id: 100,
bars: Vec::new(),
});
foos[0].bars.push(Bar {
id: 200,
content: String::new(),
});
loops(&foos);
println!("{:#?}", foos);
}

fn loops(foos: &Vec<Foo>) {
for foo in foos {
for mut bar in &foo.bars {
add_content(&mut bar);
}
}
}

fn add_content(bar: &mut Bar) {
bar.content = String::from("hello");
}
请注意,我的示例是故意的。我的实际程序涉及更多,但我试图将问题归结为让我头疼的部分。
我如何才能使以上代码正常工作?

最佳答案

显然,您不能从&mut借用&。看来您弄乱了foo bar的类型。将您的代码更改为如下所示:

fn main() {
let mut foos: Vec<Foo> = Vec::new();
foos.push(Foo {
id: 100,
bars: Vec::new(),
});
foos[0].bars.push(Bar {
id: 200,
content: String::new(),
});
loops(&mut foos); // look at here
println!("{:#?}", foos);
}

fn loops(foos: &mut Vec<Foo>) { // here
for foo in foos {
for bar in &mut foo.bars { // here
add_content(bar); // and here
}
}
}
或者
fn main() {
// the same
}

fn loops(foos: &mut Vec<Foo>) {
for foo in foos.iter_mut() {
for bar in foo.bars.iter_mut() {
add_content(bar);
}
}
}

关于rust - 突变结构内向量中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64058830/

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