4

I have a function without argument that builds and returns a Vec, and the corresponding result is always the same. I want to call that function only once and store its result in a global variable or constant that all functions in my program will be able to access. How do I do that ? My first try was to try to define a const or a static, but this is not allowed:

error[E0015]: calls in statics are limited to struct and enum constructors
 --> src/main.rs:2:30
  |
2 | static ALL: Vec<Knowledge> = Knowledge::all();
  |                              ^^^^^^^^^^^^^^^^
  |
note: a limited form of compile-time function evaluation is available on a nightly compiler via `const fn`
 --> src/main.rs:2:30
  |
2 | static ALL: Vec<Knowledge> = Knowledge::all();
  |                              ^^^^^^^^^^^^^^^^

Using let outside a function won't work either. How should I do? Yes, the error message says I could use nightly, but I don't want to do that and prefer staying with the canonic version of the language.

Fabien
  • 12,486
  • 9
  • 44
  • 62

1 Answers1

4

This depends on your case.
If you rely on stable compiler your best chance is the lazy_static crate.

If you are willing to do some experiments with the nightly compiler, you can try the const fn feature. But be aware, that there are certain limitations on what const fn can do.

hellow
  • 12,430
  • 7
  • 56
  • 79