Trait impl with long-lived data - lifetime

Use case:

  • A Trait with a method that returns a reference to some long-lived data
  • A struct impl for the trait that holds the data (it's created and cached at program startup)

A lifetime is needed to return a reference to the data, obviously.

It can't be static, because we can't prove that the struct has static lifetime (I think).

Choices:

  • Make this work with lifetimes (example?)
  • Box the data
  • Something else?

Thanks!

Boxing it alone probably won't help, but boxing it and then leaking it will, since the leak method can return a static lifetime. Then the lifetime in the trait can be static. Leaking has no drawback in a program (as opposed to a library) that needs the data for its entire duration.

2 Likes

That's cool and I hadn't considered using leak.

But I should have really said Arc, not Box!

AFAIK there is no way to do this, other than using Box::leak or wrapping in an Arc.

I mean, I think there is no way to have data in a struct instance hand out direct references, with 'static lifetime, to that data.

Someone please correct me if I'm wrong.

You could store it in a static OnceLock or (soon) LazyLock (either of which will also never destruct the value).

2 Likes

You said your other qualifier is that the data cannot be in a static variable.

I guess maybe it could, if the program were restructured.

Now:

  • The struct (Trait impl) is created from main()
  • On creation it performs a gRPC request and caches the response - this is the long-lived data

I think a static var would not work for this because they cannot be mutated.

I didn't know about OnceLock!

Using OnceLock to store a function’s previously computed value (a.k.a. ‘lazy static’ or ‘memoizing’):

Yes, it seems intended exactly for such a case.

2 Likes

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.