我想要一個鏈接列表並填充它的結構實例,但只有當列表中尚未包含我正在考慮添加的項目時。借用檢查器檢查可變引用的最佳做法是什麼?
我正在處理點,所以如果(3,5)在列表中,我不想添加它,否則我會這樣做。
我當前的代碼:
use std::collections::LinkedList;
struct Location {
x: i32,
y: i32,
}
fn main() {
let mut locations = LinkedList::new();
loop {
let location_set = &mut locations;
// Scanner stuff happens.
if !has_location(location_set, &next_checkpoint_x, &next_checkpoint_y) {
let point = Location {
x: next_checkpoint_x,
y: next_checkpoint_y,
};
locations.push_back(point);
}
}
}
fn has_location(location_list: LinkedList<Location>, target_x: &i32, target_y: &i32) -> bool {
true // Just until I can figure out this mutability stuff
}
我已經能夠得到它通過這些變化來運行,但是這似乎我錯了。
loop {
if !has_location(&mut locations, &next_checkpoint_x, &next_checkpoint_y) {
// stuff
}
}
fn has_location(location_list: &LinkedList<Location>, target_x: &i32, target_y: &i32) -> bool {
true
}
我不想has_location
能夠變異鏈表,我只是希望它能夠借用它,以便它可以看看它裏面。我不想考慮has_location
(或類似的函數)影響它檢查的鏈表。這就是我創建location_set
的原因。我想要以某種只讀的方式引用位置,並將其傳遞給has_location
函數,以及引用(位置)的函數在調用has_location
函數後不會被銷燬。我在函數的調用中傳入參數&
,因爲我不希望傳遞的參數被破壞 - 所以我希望他們借用?
是我想要的東西是有道理的 - 如果我最初聲明位置爲可變鏈表我可以傳遞它的不可變版本的函數來評估?
這是非常有用的謝謝你。在你的例子中,我不明白的東西,location_set直接傳遞給has_location(所以函數擁有它,對吧?)。在我看來,這意味着在has_location範圍的末尾,location_set應該被銷燬,不是? location_set如何繼續存在以在if塊中使用?另外,如果location_set是不可變的,那麼push_back如何能夠添加到列表的末尾,是因爲函數將可變借用強制爲不可變的借入?謝謝! – neogeek23
在答案結尾處查看我的回覆。 –