之間的區別Rust實驗編程語言Rust,我發現編譯器能夠跟蹤堆棧上某個結構體的字段的移動精確(它確切地知道什麼領域移動)。 然而,當我把結構的一個部分成Box
(即把它到堆上),編譯器不再能夠確定用於該箱的解引用後會發生一切字段級移動。它會假設「箱內」的整個結構已經移動。讓我們先來看一個例子,一切都是在棧上:Rust中的所有權跟蹤:框<T>(堆)和T(堆棧)
struct OuterContainer {
inner: InnerContainer
}
struct InnerContainer {
val_a: ValContainer,
val_b: ValContainer
}
struct ValContainer {
i: i32
}
fn main() {
// Note that the whole structure lives on the stack.
let structure = OuterContainer {
inner: InnerContainer {
val_a: ValContainer { i: 42 },
val_b: ValContainer { i: 100 }
}
};
// Move just one field (val_a) of the inner container.
let move_me = structure.inner.val_a;
// We can still borrow the other field (val_b).
let borrow_me = &structure.inner.val_b;
}
而現在相同的例子,但有一個小的改動:我們把InnerContainer
成箱(Box<InnerContainer>
)。
struct OuterContainer {
inner: Box<InnerContainer>
}
struct InnerContainer {
val_a: ValContainer,
val_b: ValContainer
}
struct ValContainer {
i: i32
}
fn main() {
// Note that the whole structure lives on the stack.
let structure = OuterContainer {
inner: Box::new(InnerContainer {
val_a: ValContainer { i: 42 },
val_b: ValContainer { i: 100 }
})
};
// Move just one field (val_a) of the inner container.
// Note that now, the inner container lives on the heap.
let move_me = structure.inner.val_a;
// We can no longer borrow the other field (val_b).
let borrow_me = &structure.inner.val_b; // error: "value used after move"
}
我懷疑它有事情做與性質堆棧主場迎戰堆,其中前者是靜態的性質(至少每堆棧幀),而後者是動態的。也許編譯器需要發揮它的安全性,因爲某些原因,我無法表達清楚/識別不夠好。
123-132是複製型的,所以數據被複制不動。 – 2keymin
但是,我對周圍的結構('ValContainer')操作,而不是所包含的整數。據我所知,自定義結構類型默認不是'Copy'able。 – MightyNicM
是的,你是對的。沒有正確閱讀你的代碼。 – 2keymin