&'static T return type

What options are there to satisfy the following function signature?

fn() -> &'static T {...}

T is a stand-in for an actual type, not a generic. I can only think of two options. Either

  • return leaked memory with something like mem::forget() or
  • return a string literal.

Is there any other possibility?
Btw, this is an academic question. I don't have an actual problem to solve.

Basically there are two options:

  1. Leaked memory.
  2. Immutable global variables.

Behind the scenes, string literals are just references to immutable global variables.


how about actual pointers to static or thread_local variables?

Do you mean raw pointers or references? If you mean references then yes, that's the same point as @alice made. If you mean raw pointers then yes sure, but my question was specifically about references to T not pointers to T because pointers don't have lifetimes.

Do you mean LocalKeys of thread locals? Thread locals themselves can be destructed / not outlast a thread, so you can't get a &'static to them; hence with.

References to nothing (a zero-sized type) is another possibility. [T] of length 0 being the built-in example. Arguably the same as global variables / statics.


I guess you can consider zero-sized types a third case.

1 Like

You can return a reference to a const value:

fn main() {}

struct SomeStruct {
    some_field: u64,

impl SomeStruct {
    const fn new() -> SomeStruct {
        Self {
            some_field: 0,

fn f() -> &'static SomeStruct {
    const S: SomeStruct = SomeStruct::new();
1 Like

This is sugar for statics (alice's #2).

See "rvalue static promotion" if you want to read up on it.

Yeah, if you have a 'static reference, then the memory lives forever. Beyond that, the only factor is whether the memory has existed since we started the program, or if it was created after startup. If it has always existed, then its fundamentally a global. Otherwise, it's leaked memory.

(And then there are zero-sized types which can just point anywhere.)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.