gpt4 book ai didi

rust - 另一个关于 cannot borrow `x` as mutable in time more than once 错误的询问

转载 作者:行者123 更新时间:2023-11-29 08:33:21 24 4
gpt4 key购买 nike

考虑以下代码:

struct Foo {
x: i32,
}

struct Test {
foos: Vec<Foo>,
v: i32,
}

fn bar(test: &mut Test, foo: &mut Foo){
// make something with test
foo.x = 42;
}

fn main() {
let test = &mut Test {
foos: vec![
Foo {x: 3},
Foo {x: 4},
],
v: 55
};

// First time test got borrowed
let iterator = test.foos.iter_mut();

for elem in iterator {
// !!Error second time test got borrowed as mutable
bar(test, elem);
}

}

假设我不能改变它的签名,有没有办法在循环中为 test.foos 的每个元素调用 bar 而不会违反唯一的 &mut 一次规则?

我能想到的唯一解决方案是在它第一次被借用为可变之前克隆测试,如:

let mut tutu = test.to_owned();
let iterator = test.foos.iter_mut();

for elem in iterator {
bar(&mut tutu, elem);
}

但是根据结构的不同,克隆结构感觉可能是昂贵的操作。

最佳答案

您链接到的 GitHub Java 示例实际上并不要求父项和子项都是可变的。事实上,父级(在您的 Java 中,这是 safebox)只会调用 getUploadUrl()

因此,我已将其稍微翻译成 Rust 语言,并使用与您的 Java 示例相似的类型名称。这个想法是方法本身只关心 URL ......所以直接传递它而不是采用可变引用:

struct Attachment {
guid: String,
}

impl Attachment {
fn new<S>(guid: S) -> Attachment
where S: Into<String>
{
Attachment { guid: guid.into() }
}

fn set_guid<S>(&mut self, guid: S)
where S: Into<String>
{
self.guid = guid.into();
}
}

struct SafeBox {
attachments: Vec<Attachment>,
upload_url: &'static str,
}

impl SafeBox {
fn get_upload_url(&self) -> &str {
self.upload_url
}
}

fn uploadAttachment(upload_url: &str, attachment: &mut Attachment) {
attachment.set_guid("12345");
}

fn main() {
let mut safebox = SafeBox {
attachments: vec![Attachment::new("12345"), Attachment::new("67890")],
upload_url: "http://upload.com/upload",
};

for mut attachment in &mut safebox.attachments {
uploadAttachment(safebox.upload_url, &mut attachment);
}
}

这是running in the playground .

作为曾尝试将简单的 C# 库移植到 Rust 的人,我可以根据经验告诉您,尝试逐行、逐类型地移植它是一个坏主意。 Rust Way (tm) 非常不同,C#(或 Java)根本无法直接移植。

关于rust - 另一个关于 cannot borrow `x` as mutable in time more than once 错误的询问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41820891/

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