'why does rust allow a local struct reference had static lifetime?

I am reading rusty_v8's source code.

And I found this code:

  let vtable: &'static RustAllocatorVtable<AtomicUsize> =
    &RustAllocatorVtable {
      allocate,
      allocate_uninitialized,
      free,
      reallocate,
      drop,
    };

https://github.com/denoland/rusty_v8/blob/main/src/array_buffer.rs#L205

I was confused that why &RustAllocatorVtable{} had static lifetime. It allocated on stack and will destroyed after the function scope, isn't it?



Solution 1:[1]

This is called rvalue static promotion or constant promotion. When the compiler faces a value that can be evaluated at compile-time, it promotes it to a static, like if you wrote:

static S: RustAllocatorVtable<AtomicUsize> = RustAllocatorVtable {
    allocate,
    allocate_uninitialized,
    free,
    reallocate,
    drop,
};
let vtable: &'static RustAllocatorVtable<AtomicUsize> = &S;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chayim Friedman