I have a data structure Document
, which I would like to serialize other Rust structs to. It is basically a HashMap
for the fields internally, however it interacts with a database API, so I will definitely want to convert other types into those Document
s.
For example this struct
struct Entry {
id: String,
user: String,
duration: u32,
location: (f64, f64),
}
I already have a conversion to the Document
type using the From
trait, however this is an extra place I have to modify when the Entry
struct changes. The implementation uses a DocumentBuilder
and looks like this:
impl From<Entry> for Document {
fn from(entry: Entry) -> Self {
Document::builder()
.name(&entry.id) // set the name of the document
.field("user", entry.user) // add fields ...
.field("duration", entry.duration)
.field("location", entry.location)
.build() // build a Document
}
}
The field
method can assign any value which can be converted to a FieldValue
to a key. So the signature of field
is:
impl DocumentBuilder {
// ...
pub fn field<T: Into<FieldValue>>(mut self, key: &str, value: T) -> Self { ... }
// ...
}
I would like to use serde and its derive feature to automatically serialize the struct and its fields into a Document
. How would I go about doing this? I looked at the wiki for Implementing a Serializer but the example shown writes to a string and I would like to know how I can serialize to a data structure using the builder pattern.
From
, as you have. – Shepmaster