在Rust中,我有以下代码:
pub trait Test: Sized {
const CONST: Self;
fn static_ref() -> &'static Self {
&Self::CONST
}
}
我的期望是,因为const
是'static
,那么我应该能够参考它也是'static
。但是,编译器给出以下错误:
error[E0515]: cannot return reference to temporary value
--> file.rs:9:9
|
9 | &Self::CONST
| ^-----------
| ||
| |temporary value created here
| returns a reference to data owned by the current function
如何在这里引入临时变量?
此外,似乎在某些情况下,对常量的引用确实有效。这是一个简短的具体示例,其中的Test实现略有不同
pub trait Test: Sized {
fn static_ref() -> &'static Self;
}
struct X;
impl Test for X {
fn static_ref() -> &'static Self {
&X
}
}
定义特征时,定义必须适用于所有可能的实现。
如果没有失败的例子,问题可能不会立即得到解决。所以假设你有这样的类型:
struct MyStruct;
impl MyStruct {
const fn new() -> Self {
MyStruct
}
}
你试图像这样实现这个特征:
impl Test for MyStruct {
const CONST: Self = MyStruct::new();
}
这不起作用,因为static_ref
的实现现在看起来像这样:
fn static_ref() -> &'static Self {
// &Self::CONST
&MyStruct::new()
}
它在函数内部创建一个值并尝试返回它。此值不是静态的,因此'static
生命周期无效。
然而,通过一些重新跳汰,你可以做一些工作:
pub trait Test: Sized + 'static {
// This is now a reference instead of a value:
const CONST: &'static Self;
fn static_ref() -> &'static Self {
Self::CONST
}
}
struct MyStruct;
impl MyStruct {
const fn new() -> Self {
MyStruct
}
}
impl Test for MyStruct {
const CONST: &'static Self = &MyStruct::new();
}
这是因为CONST
已经是'static
引用,所以函数可以返回它。所有可能的实现都必须能够获得'static
引用Self
来实现特性,因此引用一些任意本地值不再存在问题。
Rust中的常量是编译时常量,而不是具有内存位置的实际变量。 Rust编译器可以替换使用它的常量的实际值。如果您获取此类值的地址,则会获得临时地址。
Rust还具有静态变量的概念。这些变量实际上具有与整个程序持续时间一致的存储器位置,并且引用静态变量确实导致具有'static
寿命的引用。
也可以看看: