爲什麼n1_mut
在這個例子中仍然有效?它已被轉移到Option::Some
所以它不應該是無效的?爲什麼在指針移動後爲指針的成員賦值仍然有效?
struct MyRecordRec2<'a> {
pub id: u32,
pub name: &'a str,
pub next: Box<Option<MyRecordRec2<'a>>>
}
#[test]
fn creating_circular_recursive_data_structure() {
let mut n1_mut = MyRecordRec2 {
id: 1,
name: "n1",
next: Box::new(None)
};
let n2 = MyRecordRec2 {
id: 2,
name: "n2",
next: Box::new(Some(n1_mut))
};
//Why is n1_mut still valid?
n1_mut.next = Box::new(Some(n2));
}
以下不熟悉的「使用移動值的」編譯錯誤:
#[test]
fn creating_and_freezing_circular_recursive_data_structure() {
let loop_entry = {
let mut n1_mut = MyRecordRec2 {
id: 1,
name: "n1",
next: Box::new(None),
};
let n2 = MyRecordRec2 {
id: 2,
name: "n2",
next: Box::new(Some(n1_mut)),
};
n1_mut.next = Box::new(Some(n2));
n1_mut
};
}
error[E0382]: use of moved value: `n1_mut`
--> src/main.rs:44:9
|
39 | next: Box::new(Some(n1_mut)),
| ------ value moved here
...
44 | n1_mut
| ^^^^^^ value used here after move
|
= note: move occurs because `n1_mut` has type `MyRecordRec2<'_>`, which does not implement the `Copy` trait
有趣。不知道這是否算作一個錯誤 - 我不認爲你可以引發不安全因爲之後沒有辦法讀取內存。但是如果你保留一個原始指針到堆棧,你可以知道'n1Mut.next'確實被設置了:https://play.rust-lang.org/?gist=d41422bfd142c289667e7c2fb3183be0&version=undefined – trentcl
有趣的是,這是不可能的之後使用'n1_mut.next'。另外,添加一個'Drop'實現會導致:「錯誤[E0383]:部分重新初始化未初始化的結構'n1_mut'」 –