I am trying to lazy-initialize a simple tree on first access of a node.
我的树木结构:
struct Tree {
true_branch: Option<Box<Tree>>,
false_branch: Option<Box<Tree>>,
}
为了在第一次进入时实现zy化,我谨回馈一个<条码>;Result<&mut soil, &mut Religion>, 即:<条码>,(requested_node),条件是:噪音已经启动或。 Err(last_ initialized_on_the_path_to_requested_node)
如果用<代码>get_mut对工程进行罚款,但我无法获得<代码>Result版本,get_last_ initialized_
impl Tree {
fn get_mut(&mut self, mut directions: impl Iterator<Item = bool>) -> Option<&mut Self> {
let mut current = self;
loop {
match directions.next() {
None => break,
Some(true) => {
current = current.true_branch.as_deref_mut()?;
}
Some(false) => {
current = current.false_branch.as_deref_mut()?;
}
}
}
Some(current)
}
/// This does not compile
fn get_last_initialized_mut(&mut self, mut directions: impl Iterator<Item = bool>) -> Result<&mut Self, &mut Self> {
let mut current = self;
loop {
match directions.next() {
None => break,
Some(true) => {
let next = current.true_branch.as_deref_mut();
if next.is_none() {
drop(next);
return Err(current);
} else {
current = next.unwrap();
}
}
Some(false) => {
let next = current.false_branch.as_deref_mut();
if next.is_none() {
drop(next);
return Err(current);
} else {
current = next.unwrap();
}
}
}
}
Ok(current)
}
}
The error:
error[E0499]: cannot borrow `*current` as mutable more than once at a time
--> src/lib.rs:36:36
|
27 | fn get_last_initialized_mut(&mut self, mut directions: impl Iterator<Item = bool>) -> Result<&mut Self, &mut Self> {
| - let s call the lifetime of this reference ` 1`
...
33 | let next = current.true_branch.as_deref_mut();
| ---------------------------------- first mutable borrow occurs here
...
36 | return Err(current);
| ^^^^^^^ second mutable borrow occurs here
...
52 | Ok(current)
| ----------- returning this value requires that `current.true_branch` is borrowed for ` 1`
我没有看到的是,我通过第33行的<代码>ext借阅了next
。
我尝试用um子打碎,根据破碎类型返回 lo门外,放弃变量。 他们都没有工作。