在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
,因此引用某个任意局部值不再是问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句