How to save Rust data created during runtime to be loaded at compile time?

I have a Rust struct that contains many fields that I populate with values from API requests during runtime. Is there a way to start my app with this data loaded at compile time?

I need the data as a struct by the time compilation is finished.

I was thinking of saving the struct as a Rust file with the populated values. Are there any existing solutions that do something similar?

Only thing that comes to mind is a proc macro.

I reckon you could probably do that with a Rust build script: Build Scripts - The Cargo Book

Basically a Rust file, build.rs, is compiled and run before cargo builds you Rust program. Seems likely that build.rs could fetch data from an API request and write out a suitable Rust source file that would contain your structure creations.

I have had some luck with a simple example of a build.rs that emitted rust code to be used in my program proper so this might work for you.

1 Like

Does this work?

  • serde::serialize at runtime,
  • include_bytes @ compile time, serde::deserialize @ runtime
2 Likes

If you relax this requirement a little, you could store a recorded API response as a text file and use include_str! or include_bytes! to save it in a static variable. On application start, you can then parse that string into your actual data structure.

I am aware of saving to use serde/bincode to serialize back at runtime but that is not a compile-time solution.

I'm aware of using build.rs. Outputting a struct filled with data as a Rust file - anyone know how to do that?

I can output Rust code as an struct definition like so
pub struct Example { pub name: String }

but that is not the same as a struct prefilled with data
let example = Example{ name: "e" }
My question is turning a struct prefilled with data during runtime to be loaded at compile-time.

Check out the code generation example here. If you generate code like the snippet below, it should satisfy your goal:

const PRECOMPUTED: Example = Example { name: "e" };

Note that in many cases, the default Debug formatting is valid Rust code. You may be able to use that to easily generate the code.

Yes format!("{:#?}",my_struct) satisfies

You should be aware that the output of Debug is explicitly unstable, so this may break for you in the future.

3 Likes