gpt4 book ai didi

rust - 如何在成员函数中修改结构的可选字段

转载 作者:行者123 更新时间:2023-11-29 08:18:35 25 4
gpt4 key购买 nike

我有一个结构 Struct,可以选择包含 SubStructSubStruct 包含一个字段。我想调用 Structmodify 成员方法,它调用 SubStructmodify_field 成员方法修改SubStruct

field 字段

这个和其他题中提到的不同,不是直接修改字段,而是调用成员方法依次修改字段。直接修改字段有共享的解决方案我看过。

struct SubStruct {
field: u32,
}

impl SubStruct {
fn modify_field(&mut self) {
self.field = 2
}
}

struct Struct {
sub: Option<SubStruct>,
}

impl Struct {
fn modify(&mut self) {
if let Some(ref mut sub) = self.sub { // no reference before Some
sub.modify_field();

self.do_something();
}
}

fn do_something(&self) {
}
}

fn main() {
let sub = Some(SubStruct{field: 1});
let mut structure = Struct{ sub };

structure.modify();

println!("{}", structure.sub.unwrap().field);
}

( playground

我尝试了很多变体,但都没有成功,在我当前的版本中,我遇到了这个错误:

error[E0502]: cannot borrow `*self` as immutable because `self.sub.0` is also borrowed as mutable
--> src/main.rs:20:13
|
17 | if let Some(ref mut sub) = self.sub { // no reference before Some
| ----------- mutable borrow occurs here
...
20 | self.do_something();
| ^^^^ immutable borrow occurs here
21 | } | - mutable borrow ends here

如您所见,它似乎与 self.do_something()self 的不可变借用有关,其中对 self< 的可变借用 已经被带入了函数参数。

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