我有以下代码编译:为什么接受Box <MyType>的函数会在接受自我的函数有效时移动值?
pub mod Btree {
pub struct node {
pub id: u32,
pub red: bool,
pub left: Option<Box<node>>,
pub right: Option<Box<node>>,
}
impl<'a> node {
pub fn insert(mut node_: Option<Box<node>>, id: u32) -> Option<Box<node>> {
match node_ {
None => Some(Box::new(node {
id: id,
red: true,
left: None,
right: None,
})),
Some(x) => x.insert_(id),
}
}
pub fn insert_(mut self, id: u32) -> Option<Box<node>> {
self.left = node::insert(self.left, id);
Some(Box::new(self))
}
}
}
当我改变insert_()
有Box<node>
,而不是工作:
pub mod Btree {
pub struct node {
pub id: u32,
pub red: bool,
pub left: Option<Box<node>>,
pub right: Option<Box<node>>,
}
impl<'a> node {
pub fn insert(mut node_: Option<Box<node>>, id: u32) -> Option<Box<node>> {
match node_ {
None => Some(Box::new(node {
id: id,
red: true,
left: None,
right: None,
})),
Some(x) => node::insert_(x, id),
}
}
pub fn insert_(mut node_: Box<node>, id: u32) -> Option<Box<node>> {
node_.left = node::insert(node_.left, id);
Some(node_)
}
}
}
我得到:
error[E0382]: use of partially moved value: `node_`
--> src/main.rs:23:13
|
23 | node_.left = node::insert(node_.left, id);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^----------^^^^^
| | |
| | value moved here
| value used here after move
|
= note: move occurs because `node_.left` has type `std::option::Option<std::boxed::Box<Btree::node>>`, which does not implement the `Copy` trait
我不明白那是什么。代码非常相似,在这两种情况下都有一个动作。
我觉得代码OP *想*后为[这样的事情(https://play.rust-lang.org/?gist=39776f2b5554c07a764ebda48939d2dc&version=stable)。 – user4815162342
锈标准命名说,你的模块应该是snake_case('btree'),你的类型应该是PascalCase('Node')。你的变量不应该有尾部下划线('node_')。你的一生('<'a>')没有效果,应该被删除。 – Shepmaster