rust - 如何在编译过程中注释代码以生成工件?

标签 rust rust-cargo serde

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

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/

相关文章:

struct - '&self'和 '&' a self'有什么区别?

recursion - 递归宏使无限递归

rust - 为什么没有为明确实现的类型实现特征?

rust - 如何在自定义结构序列化程序中嵌套字段?

json - 如何对 JSON 对象进行 key 不可知的反序列化?

rust - 什么使某些东西成为 "trait object"?

performance - 为什么我的递归 Fibonacci 实现与迭代实现相比如此缓慢?

database - 如何将 Diesel 与 SQLite 连接一起使用并避免 `database is locked` 类型的错误

rust - 删除 Rust 中的默认链接器标志

rust - Cargo 是否支持自定义配置文件?