我有一個恆定的形式定義的陣列,任何函數外:迭代查找,臨時值下降,同時仍然借
const VALUES: [(char, &str); 2] = [('A', "abc"), ('B', "acb")];
我試圖使用find()
方法位於Iterator
,在爲了從一個基於謂詞的數組中提取單個元素:
VALUES.iter().find(|&&(name, _)| name == 'A');
在這種形式下,它工作正常。但是,我無法將找到的元素評估爲任何內容,因爲只要我嘗試創建綁定,嘗試綁定結果,根據文檔應該返回爲Option<T>
。
讓我們改變第二行是不工作:
const VALUES: [(char, &str); 2] = [('A', "abc"), ('B', "acb")];
fn main() {
let result = VALUES.iter().find(|&&(name, _)| name == 'A');
}
人們會想到這個返回Option<T>
作爲根據文檔,而是我回來編譯錯誤:
error: borrowed value does not live long enough
--> src/main.rs:4:63
|
4 | let result = VALUES.iter().find(|&&(name, _)| name == 'A');
| ------ temporary value created here ^temporary value dropped here while still borrowed
5 | }
| - temporary value needs to live until here
|
= note: consider using a `let` binding to increase its lifetime
我完全困惑;我確定我剛剛與「借閱檢查器」搞混了。也許有人可以指出我正確的方向?
Const數組實際存在於內存中。 [此代碼](https://play.rust-lang.org/?gist=023a4c4ea0cc8cac7a890bbd3a05d876&version=stable&backtrace=0)有效。被刪除的臨時值不是數組,而是數組片。 – red75prime
@ red75prime:我的理解是*那*行爲是一種特殊情況,即立即借用的臨時對象被提升,因爲這種模式比較常見,否則會更加痛苦。 –
另一種選擇是使用「靜態」,它存在於內存中,因此可以正常借用。 – zstewart