我有一个恒定的形式定义的阵列,任何函数外:迭代查找,临时值下降,同时仍然借
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