rust 无法返回对临时值的引用,但所有内容都是“static

ogq8wdun  于 2023-10-20  发布在  其他
关注(0)|答案(2)|浏览(140)

我正在尝试从静态值示例化一个结构。编译器说我正在创建一个临时值,但所有内容都是引用和静态的。我找到了this github issue,它看起来像我的问题。

  1. struct OutputDescription {
  2. name: &'static str,
  3. }
  4. struct SubOutput<T> {
  5. sub_param_a: T,
  6. }
  7. struct Output {
  8. param_a: SubOutput<bool>
  9. }
  10. impl <T: Description>Description for SubOutput<T> {
  11. fn name() -> &'static str {
  12. "param_a"
  13. }
  14. fn fields() -> &'static [OutputDescription] {
  15. &[OutputDescription {
  16. name: T::name(),
  17. }]
  18. }
  19. }
  20. trait Description {
  21. fn name() -> &'static str;
  22. fn fields() -> &'static [OutputDescription];
  23. }
  1. Compiling playground v0.0.1 (/playground)
  2. error[E0515]: cannot return reference to temporary value
  3. --> src/main.rs:19:9
  4. |
  5. 19 | &[OutputDescription {
  6. | _________^-
  7. | |_________|
  8. | ||
  9. 20 | || name: T::name(),
  10. 21 | || }]
  11. | || ^
  12. | ||__________|
  13. | |__________returns a reference to data owned by the current function
  14. | temporary value created here
  15. For more information about this error, try `rustc --explain E0515`.
  16. error: could not compile `playground` (bin "playground") due to previous error

Playground
我正在寻找一个修复或解决办法,如果这是一个编译器的问题。

iqjalb3h

iqjalb3h1#

你不能在编译时调用trait函数,所以不可能通过调用trait函数来构造静态值。但是由于你的函数没有参数,你可以使用const s代替fn s:

  1. trait Description {
  2. const NAME: &'static str;
  3. const FIELDS: &'static [OutputDescription];
  4. }
  5. impl<T: Description> Description for SubOutput<T> {
  6. const NAME: &'static str = "param_a";
  7. const FIELDS: &'static [OutputDescription] = &[OutputDescription { name: T::NAME }];
  8. }

当然,这禁止返回值不是常量的实现。

xzlaal3s

xzlaal3s2#

  1. [OutputDescription {
  2. name: T::name(),
  3. }]

是一个临时的,如果它可以被提升为一个常量-因此,如果你可以采取一个静态引用它-取决于几个因素,调用一个函数,如T::nameprevents it,因此,你不会得到常量提升,因此,你不能返回一个静态引用它。

相关问题