rust - 如何在编译期间注释代码以生成工件?
问题描述
我有一个这样的配置结构:
pub struct Configuration {
flag1: bool,
flag2: String,
flag3: i32,
flag4: String
}
我想生成一个用户可以使用值编辑的配置文件模板。我将允许用户在启动时传递配置文件并将其加载到配置结构中。
有没有办法通过某种注释来生成这个工件?
我正在成像类似于“ serde
”但生成文件的东西:
#[derive(Template)] // create the file during build
pub struct Configuration {
#[template(default = true)] // set some sort of defaults for the template file
flag1: bool,
#[template(default = "yes")]
flag2: String,
#[template(default = 42)]
flag3: i32,
#[template(default = "no")]
flag4: String
}
结果将是一个文件,如:
flag1: true
flag2: "yes"
flag3: 42
flag4: "no"
解决方案
这看起来像askama。它具有可扩展的模板语法和对 HTML 的特殊支持。
生锈示例:
#[derive(Template)] // this will generate the code...
#[template(path = "sample.conf", escape = "none")]
struct SampleConfig<'a> { // the name of the struct can be anything
b: &'a str,
c: Some(&'a str),// the field name should match the variable name
// in your template
}
模板(在 /templates/sample.conf 中):
field b: {{ b }}
{% match c %}
{% when Some with (val) %}
field c: {{ val }}
{% when None %}
field c: some default
{% endmatch %}
你可以在书中看到更多的例子
PS:据我所知,默认语法是不可能的,需要用匹配来处理。但请记住,您的模板将在编译时进行预处理并打包到您的二进制文件中。
推荐阅读
- javascript - 如何在每个图标上单独更改颜色?反应,样式化的组件
- c++ - C++:识别事件系统中的多态事件
- flutter - Flutter 在根小部件上显示 Snackbar
- javascript - 跟踪具有多个值的事件。闪亮的 io。R
- javascript - 如何将二进制文件转换为可下载的文件扩展名?
- javascript - JavaScript井字游戏没有让玩家获胜
- javascript - 如何将元素附加到我的引导模式以显示来自本地存储的数据?
- tinymce - 以 RGB 而不是 Hex 返回 TinyMCE 颜色?
- go - 使用 Mutate 准入控制器修改 deploymnet 中的 ImagePullPolicy
- android - Android Studio - 库模块内的库模块