我有一个这样的配置结构:
pub struct Configuration {
flag1: bool,
flag2: String,
flag3: i32,
flag4: String
}
我想生成一个配置文件模板,用户可以使用值进行编辑。我将允许用户在启动时传递配置文件并将其加载到config结构中。有没有办法通过某种注释生成此工件?
我正在成像类似于“
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的特殊支持。
Rust示例:
#[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 %}
您可以在book中看到更多示例PS:
据我所知,默认语法是不可能的,需要使用match进行处理。尽管请记住,您的模板将在编译时进行预处理,并打包到您的二进制文件中。
关于rust - 如何在编译过程中注释代码以生成工件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64782904/