无法返回对临时值的引用,但一切都是“静态”的

问题描述 投票:0回答:1

我正在尝试从静态值实例化一个结构。编译器说我正在创建一个临时值,但所有内容都是引用的且是静态的。我发现: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

游乐场:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=68ec8292d5306c3ea380148c0bc1613a

如果这是编译器问题,我正在寻找修复或解决方法。

谢谢,br

菲利克斯

rust reference static
1个回答
0
投票

这个

[OutputDescription {
    name: T::name(),
}]

是一个临时的,它是否可以提升为常量取决于几个因素,

T::name
不是
const
会阻止它,因此你不会得到不断的提升,因此你不能返回对它的静态引用。

© www.soinside.com 2019 - 2024. All rights reserved.