Rust 解决红黑树实现中的生存期冲突

Rust 解决红黑树实现中的生存期冲突,rust,lifetime,borrow-checker,red-black-tree,Rust,Lifetime,Borrow Checker,Red Black Tree,我一直在和锈迹斑斑的红黑树玩耍。守则(目前的情况)如下: 使用std::cmp::PartialOrd; 使用std::fmt::Display; 结构RedBlackNode RedBlackNode{ fn eq(&self,其他:&self)->bool{ self.elem==其他.elem } } 发布结构RedBlackTree>, } 恳求{ pub fn new()->Self{ RedBlackTree::{root:None} } 发布fn添加(&mut self,元素:T)

我一直在和锈迹斑斑的红黑树玩耍。守则(目前的情况)如下:

使用std::cmp::PartialOrd;
使用std::fmt::Display;
结构RedBlackNode RedBlackNode{
fn eq(&self,其他:&self)->bool{
self.elem==其他.elem
}
}
发布结构RedBlackTree>,
}
恳求{
pub fn new()->Self{
RedBlackTree::{root:None}
}
发布fn添加(&mut self,元素:T){
设z:RedBlackNode){
未执行!();
}
fn右旋转(&mut self,z:&mut RedBlackNode){
如果z.parent.is_none(){
返回;
}
而z.parent.unwrap()颜色{
如果z.parent.unwrap().parent.is_some()
&&*z.parent.unwrap()
==*z.parent.unwrap().parent.unwrap().left.unwrap()
{
设y=z.parent.unwrap().parent.unwrap().right.unwrap();
如果是y颜色{
z、 parent.unwrap().color=false;
y、 颜色=假;
z、 parent.unwrap().parent.unwrap().color=true;
z=z.parent.unwrap().parent.unwrap();
}否则{
如果z.parent.unwrap().right.is_some()
&&*z==*z.parent.unwrap().right.unwrap()
{
z=z.parent.unwrap();
自左旋转(z);
}
z、 parent.unwrap().color=false;
z、 parent.unwrap().parent.unwrap().color=true;
自旋转(z.parent.unwrap().parent.unwrap());
}
}否则{
如果z.parent.unwrap().parent.is_some()
&&*z.parent.unwrap()
==*z.parent.unwrap().parent.unwrap().right.unwrap()
{
设y=z.parent.unwrap().parent.unwrap().left.unwrap();
如果是y颜色{
z、 parent.unwrap().color=false;
y、 颜色=假;
z、 parent.unwrap().parent.unwrap().color=true;
z=z.parent.unwrap().parent.unwrap();
}否则{
如果z.parent.unwrap().left.is_some()
&&*z==*z.parent.unwrap().left.unwrap()
{
z=z.parent.unwrap();
自右旋(z);
}
z、 parent.unwrap().color=false;
z、 parent.unwrap().parent.unwrap().color=true;
self.left_旋转(z.parent.unwrap().parent.unwrap());
}
}
}
}
self.root.unwrap().color=false;
}
}
fn打印节点(节点:&RedBlackNode)
哪里
T:显示器,
{
匹配&node.left{
一些(l)=>打印节点(l),
无=>{}
};
println!(“{}”,node.elem);
匹配&node.right{
一些(r)=>打印节点(r),
无=>{}
};
}
发布fn打印树(树:&RedBlackTree)
哪里
T:显示器,
{
匹配&tree.root{
Some(root)=>print_节点(&root),
无=>{}
};
}
fn main(){
让我的树:RedBlackTree=RedBlackTree::new();
打印目录树(&my目录树);
}
但是,编译器由于第43行的生存期冲突而投诉:

错误[E0495]:由于需求冲突,无法推断自动引用的适当生存期
-->src/main.rs:43:68
|
43 |让mut x:Option>=self.root.as|u mut();
|                                                                    ^^^^^^
|
注意:首先,生命周期不能超过39:5在方法体上定义的匿名生命周期#1。。。
-->src/main.rs:39:5
|
39 |/pub fn添加(&mut self,elem:T){
40 | |设z:RedBlackNode src/main.rs:34:6
|
34 | impl{
|      ^^
注意:…因此表达式是可赋值的
-->src/main.rs:43:58
|
43 |让mut x:Option>=self.root.as|u mut();
|                                                          ^^^^^^^^^^^^^^^^^^
=注意:应为'std::option::option>`

找到`std::option::option帮你一个忙:在尝试用Rust编写任何递归定义的数据结构之前先阅读。你可以这样做,但一般来说,你要么将性能留在表上(就像在Java等托管语言中一样),要么使用大量不安全的
(就像在C中一样,因为那里的一切都是不安全的)。这回答了你的问题吗?