What are the downsides of using static lifetime?

Hi everyone, i am just wondering if there are downsides of using static lifetime and what are they ? Also i would like to know what is happening with variable which has static lifetime ?

Thank you :slight_smile:

If you may have static lifetime you generally want to have it, there is no downsides. Point is, that you don't always can have static lifetime - for references for eg. Transmuting to align lifetime is (almost?) always an unsafe operation, and in general indicates architectural problems - this is one of things which can be avoided by proper design.

1 Like

A reference with a static lifetime means that the referenced object must live for the entire life of the program. There are two main ways to create static references:

  • Create a static variable or a literal with a value known at compile time
  • Use Box::leak to create a static reference from a dynamically created value

Static variables are good to use whenever you have a value known at compile time, but obviously, you can't do that for any dynamically calculated values.

Box::leak may be fine to use for some global one-time initializations, but is obviously unsuited for handling large amounts of data because you can't deallocate it (that's why it's called leak).

So when you're dealing with some regular values (like a vector of data supplied by the program's caller), it's unlikely that you will be able to handle that using static references. However, note that any type that owns its contents (like Vec<T>) satisfies the 'static lifetime bound, so every time you use owning types, you technically use the static lifetime.

3 Likes