[英]Rust compiler does not expect a mutable reference where a mutable reference should be expected
We are writing a function to erase a node from a sorted tree in Rust, but are stuck with the Rust compiler complaining that it expects no mutable reference when the called function does need a mutable reference:我们正在编写一个函数来从 Rust 中的排序树中删除一个节点,但是被 Rust 编译器困住了,抱怨它在被调用的函数确实需要一个可变引用时不需要可变引用:
error[E0308]: mismatched types
--> src/tree.rs:111:17
|
111 | SortedContainer::node_find_parent(&mut Some(node), &age, &name)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `std::option::Option`, found mutable reference
|
= note: expected type `std::option::Option<std::boxed::Box<tree::Node>>`
found type `&mut std::option::Option<std::boxed::Box<tree::Node>>`
This is our code snippet in the impl block of SortedContainer (Our tree structure):这是我们在 SortedContainer 的 impl 块中的代码片段(我们的树结构):
fn node_find_parent<'a>(parent_option: &'a mut Option<Box<Node>>, age: &i32, name: &String) -> &'a mut Option<Box<Node>> {
// TODO: implement
parent_option
}
pub fn find_parent(&mut self, age: &i32, name: &String) -> &mut Option<Box<Node>> {
&mut match self.root {
Some(node) => if node.name == *name && node.age == *age {
self.root
} else {
SortedContainer::node_find_parent(&mut Some(node), &age, &name)
}
None => &mut None,
}
}
The SortedContainer::node_find_parent
should return a mutable reference, since the return type is a mutable reference SortedContainer::node_find_parent
应该返回一个可变引用,因为返回类型是一个可变引用
What are we are doing wrong?我们做错了什么?
Changing the &mut match
to match &mut
solved the problems:将&mut match
更改为match &mut
解决了问题:
pub fn find_parent(&mut self, age: &i32, name: &String) -> &mut Option<Box<Node>> {
match &mut self.root {
Some(node) => {
if node.name == *name && node.age == *age {
&mut self.root
} else {
SortedContainer::node_find_parent(&mut self.root, &age, &name)
}
}
None => &mut None,
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.