以下终身省略有效:
struct X;
impl X {
const ONE: &str = "one";
}
为什么以下不起作用?
struct X;
impl X {
const TWO: &[&str] = &["two"];
}
编译器抱怨不同的生命周期,而所有生命周期都应该是
'static
:
error[E0491]: in type `&[&str]`, reference has a longer lifetime than the data it references
--> src/lib.rs:6:5
|
6 | const TWO: &[&str] = &["two"];
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
有趣的是,在 impl
块的
outside,代码可以正常工作。但这对寿命应该没有影响。
这是一个已知的错误 造成的原因是
impl Foo { const CONST: &str = ""; }
脱糖是为了:
impl<'a> Foo<'a> { const CONST: &'a str = ""; }
解决方法是直接指定正确的生命周期:
struct X;
impl X {
const TWO: &[&'static str] = &["two"];
}