我正在尝试从静态值实例化一个结构。编译器说我正在创建一个临时值,但所有内容都是引用的且是静态的。我发现:https://github.com/rust-lang/rust/issues/69574,它看起来像我的问题。
struct OutputDescription {
name: &'static str,
}
struct SubOutput<T> {
sub_param_a: T,
}
struct Output {
param_a: SubOutput<bool>
}
impl <T: Description>Description for SubOutput<T> {
fn name() -> &'static str {
"param_a"
}
fn fields() -> &'static [OutputDescription] {
&[OutputDescription {
name: T::name(),
}]
}
}
trait Description {
fn name() -> &'static str;
fn fields() -> &'static [OutputDescription];
}
fn main() {}
Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return reference to temporary value
--> src/main.rs:19:9
|
19 | &[OutputDescription {
| _________^-
| |_________|
| ||
20 | || name: T::name(),
21 | || }]
| || ^
| ||__________|
| |__________returns a reference to data owned by the current function
| temporary value created here
For more information about this error, try `rustc --explain E0515`.
error: could not compile `playground` (bin "playground") due to previous error
如果这是编译器问题,我正在寻找修复或解决方法。
谢谢,br
菲利克斯
这个
[OutputDescription {
name: T::name(),
}]
是一个临时的,它是否可以提升为常量取决于几个因素,
T::name
不是const
会阻止它,因此你不会得到不断的提升,因此你不能返回对它的静态引用。