简体   繁体   中英

Can Rust macros parse JSON?

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?

There are multiple ways to parse json at compile-time. In order of "involvement":

  • using the build.rs script to generate your source code during build; it's technically cheating, of course, but it's easy,
  • using a 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,
  • writing a compiler plugin, which is what 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM