fn default_values() -> &'static [u32] {
static VALUES: [u32; 3] = [1, 2, 3];
&VALUES
}
fn main() {
let values: [u32; 3] = [4, 5, 6];
let optional_values: Option<&[u32]> = Some(&values);
// this compiles and runs fine
let _v = optional_values.unwrap_or_else(|| default_values());
// this fails to compile
let _v = optional_values.unwrap_or_else(default_values);
}
最后一个语句无法编译,报错为:
error[E0597]: `values` does not live long enough
--> src/main.rs:8:49
|
8 | let optional_values: Option<&[u32]> = Some(&values);
| ^^^^^^ borrowed value does not live long enough
...
12 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
我想知道:
- 是什么导致了最后两个语句之间的行为差异
- 第一个
unwrap_or_else(|| default_values())
是否是处理此问题的正确方式,还是有更好的方式
default_values as fn() -> &'static _
然后它就可以工作了。 - DanSnowfeature(nll)
提供了额外的信息:*'borrowed value does not live long enough, cast requires thatvalues
is borrowed for'static
'* - hellow_v
,实际上只需要as fn() -> _
就足够了。这只是一个“你需要帮助编译器”的情况。 - Stargateur