我有以下代碼編譯:爲什麼接受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