How can I efficiently organize static data that isn't trivial to initialize in my code?

I'm trying to use the fontdue crate for text rendering, and I want to have a variety of fonts easily available throughout my program. My first idea is to do something like this for each font, then allowing me to pass around &'static Font instances very conveniently:

pub static ROBOTO: Font = {
    let font = include_bytes!("roboto/Roboto-Regular.ttf") as &[u8];
    Font::from_bytes(font, FontSettings::default()).unwrap()
};

but this produces numerous errors:

error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
 --> src/text_rendering.rs:8:28
  |
8 |     Font::from_bytes(font, FontSettings::default()).unwrap()
  |                            ^^^^^^^^^^^^^^^^^^^^^^^

error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
 --> src/text_rendering.rs:8:5
  |
8 |     Font::from_bytes(font, FontSettings::default()).unwrap()
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
 --> src/text_rendering.rs:8:5
  |
8 |     Font::from_bytes(font, FontSettings::default()).unwrap()
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I understand these errors, but I don't have any ideas for how to fix them.

Use lazy_static instead, which should do exactly what you want.

An increasing number of people are using the once_cell crate, which doesn't require macros. It's also the basis for standard lazy types, which currently have an RFC up.

Not disagreeing on lazy_static just pointing out that there are alternatives.

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.