I'd like to define constant values by using a JSON configuration file, something like this:
enum E {
ONE = get!(include_json!("a.json"), 0),
TWO = get!(include_json!("a.json"), 1),
}
Is there any way to parse JSON at compile-time?
An easy way create Value s is with the serde_json::json macro. This essentially allows you to write JSON directly in Rust source code. If you have a Value representing an object or array, you can access the fields using Value::get , similar to Vec::get and HashMap::get .
In Rust Macros are executed at compile time. They generally expand into new pieces of code that the compiler will then need to further process.
Rust has excellent support for macros. Macros enable you to write code that writes other code, which is known as metaprogramming. Macros provide functionality similar to functions but without the runtime cost. There is some compile-time cost, however, since macros are expanded during compile time.
There are multiple ways to parse json at compile-time. In order of "involvement":
build.rs
script to generate your source code during build; it's technically cheating, of course, but it's easy,const
function in combination with the include_str!
, it would require nightly and I am not sure whether the compile-time engine is powerful enough at the time being,include_str!
is, it also requires nightly and the interface may change with each release of the compiler.Thus I would advise you to use the build.rs
script approach for now since it's both simple and stable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With