如何使用 serde 将 Rust 对象序列化为 Rust 文字?
How can I serialise Rust object to Rust literals using serde?
我想在代码生成中使用 serde,将一些复杂的嵌套对象迭代嵌入到生成的代码中。
我不希望 serde 产生除以下形式之外的任何东西:
const FOO: Foo = Foo {
bar: 0,
baz: Baz {
quux: 1
}
};
(也许我提供 const FOO: Foo =
。)
Ron 似乎是要使用的板条箱,但看起来它不会为文字值生成 Rust 语法。
我是不是误解了它的用途?
要按字面意思执行您要求的操作,您需要 write a custom Serde serializer. It will be a bit of work to get all the details right. Most literals (e.g. strings, characters and numbers) can be serialized to valid Rust literals using the Display
implementation of proc_macro2::Literal
,这将处理转义特殊字符、在需要时为浮点数添加 .0
后缀以及类似的细节。但是,看起来为结构实现序列化程序将取决于您。
Rust 中最常见的代码生成方法是 writing a proc macro, and using the quote crate 发出源代码。我对您的用例了解不够,无法判断这是否是解决您问题的有用方法。
我想在代码生成中使用 serde,将一些复杂的嵌套对象迭代嵌入到生成的代码中。
我不希望 serde 产生除以下形式之外的任何东西:
const FOO: Foo = Foo {
bar: 0,
baz: Baz {
quux: 1
}
};
(也许我提供 const FOO: Foo =
。)
Ron 似乎是要使用的板条箱,但看起来它不会为文字值生成 Rust 语法。
我是不是误解了它的用途?
要按字面意思执行您要求的操作,您需要 write a custom Serde serializer. It will be a bit of work to get all the details right. Most literals (e.g. strings, characters and numbers) can be serialized to valid Rust literals using the Display
implementation of proc_macro2::Literal
,这将处理转义特殊字符、在需要时为浮点数添加 .0
后缀以及类似的细节。但是,看起来为结构实现序列化程序将取决于您。
Rust 中最常见的代码生成方法是 writing a proc macro, and using the quote crate 发出源代码。我对您的用例了解不够,无法判断这是否是解决您问题的有用方法。