我正在创建一个带有这样定义的节点的二叉树:
use std::cell::{Ref, RefCell};
pub struct Node<T>
where
T: Copy + PartialOrd + std::fmt::Display,
{
data: T,
left: Option<RefCell<Box<Node<T>>>>,
right: Option<RefCell<Box<Node<T>>>>,
}
我正在尝试实现一个函数find
,该函数应该带有一个根节点和一个密钥,并返回对与给定密钥匹配的节点的引用。我试图递归地实现find
,但是在从Option
和RefCell
中取出左右子树时遇到了麻烦。
fn find<T>(node: Ref<Box<Node<T>>>, data: T) -> Option<Ref<Box<Node<T>>>>
where
T: Copy + PartialOrd + std::fmt::Display,
{
if node.data == data {
return Some(node);
} else if node.data > data {
if node.left.is_some() {
// Error: Cannot move out of borrowed content
let myref = node.left.unwrap().borrow();
return find(myref, data);
} else {
return None;
}
} else {
if node.right.is_some() {
// Error: returns a value referencing data owned by the current function
let myref = node.right.as_ref().unwrap().borrow();
return find(myref, data);
} else {
return None;
}
}
}
error[E0507]: cannot move out of borrowed content
--> src/lib.rs:21:25
|
21 | let myref = node.left.unwrap().borrow();
| ^^^^^^^^^ cannot move out of borrowed content
error[E0515]: cannot return value referencing temporary value
--> src/lib.rs:22:20
|
21 | let myref = node.left.unwrap().borrow();
| ------------------ temporary value created here
22 | return find(myref, data);
| ^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
error[E0515]: cannot return value referencing function parameter `node`
--> src/lib.rs:30:20
|
29 | let myref = node.right.as_ref().unwrap().borrow();
| ---- `node` is borrowed here
30 | return find(myref, data);
| ^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function