简体   繁体   English

Rust宏可以解析JSON吗?

[英]Can Rust macros parse JSON?

I'd like to define constant values by using a JSON configuration file, something like this: 我想通过使用JSON配置文件来定义常量值,如下所示:

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? 有没有办法在编译时解析JSON?

There are multiple ways to parse json at compile-time. 在编译时有多种方法可以解析json。 In order of "involvement": 按照“参与”的顺序:

  • using the build.rs script to generate your source code during build; 使用build.rs脚本在构建期间生成源代码; it's technically cheating, of course, but it's easy, 当然,它在技术上是作弊,但它很容易,
  • using a const function in combination with the include_str! const函数与include_str!结合使用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! 编写一个编译器插件,这就是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. 因此,我建议您现在使用build.rs脚本方法,因为它既简单又稳定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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