How to get a static reference of a generic constant?

⚓ Rust    📅 2025-09-10    👤 surdeus    👁️ 9      

surdeus

Warning

This post was published 64 days ago. The information described in this article may have changed.

This trait cannot be compiled

trait GetConst {
    type Get: Copy;
    const GET: Self::Get;
    
    fn get() -> &'static Self::Get {
        &Self::GET
    }
}

which gives an error

error[E0515]: cannot return reference to temporary value
 --> src/lib.rs:8:9
  |
8 |         &Self::GET
  |         ^---------
  |         ||
  |         |temporary value created here
  |         returns a reference to data owned by the current function

For more information about this error, try `rustc --explain E0515`.

I know some types with destructors that can be put in constant, like Vec<T>, which makes itself cannot be static. But is there some trait bound that can constrain a type to must have no destructor, to prevent something like Vec<T> , make this example compile? Thanks.

3 posts - 3 participants

Read full topic

🏷️ Rust_feed