首页 > 解决方案 > 如何在编译期间注释代码以生成工件?

问题描述

我有一个这样的配置结构:

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"

标签: rustrust-cargoserde

解决方案


这看起来像askama。它具有可扩展的模板语法和对 HTML 的特殊支持。

生锈示例:

#[derive(Template)] ​// this will generate the code...​
#[template(path = ​"sample.conf", escape = "none"​)]
​struct​ ​SampleConfig<​'​a​&gt; { ​// 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:据我所知,默认语法是不可能的,需要用匹配来处理。但请记住,您的模板将在编译时进行预处理并打包到您的二进制文件中。


推荐阅读