在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
}
}