使用 Serde 将结构实例写入文件时如何向结构实例添加额外的数据点?

How to add an additional data point to an instance of a struct when writing it to a file with Serde?

一个Person有一个first_name和一个last_name。将 Person 的实例写入 CSV 时,如何将 time 导出添加到 CSV?

#[macro_use]
extern crate serde_derive;
extern crate csv;
extern crate serde;

use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Serialize, Deserialize)]
struct Person {
    first_name: String,
    last_name: String,
}

fn current_ms() -> u64 {
    let since_the_epoch = &SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    let ms = since_the_epoch.as_secs() * 1000 + since_the_epoch.subsec_nanos() as u64 / 1_000_000;
    ms
}

fn main() {
    let person = Person {
        first_name: "Craig".to_string(),
        last_name: "David".to_string(),
    };
    let file_path = std::path::Path::new("test.csv");
    let mut wtr = csv::Writer::from_path(file_path).unwrap();
    wtr.serialize(&person).unwrap();
    println!("{}", current_ms());
}

以上代码导致:

>>> cat test.csv
first_name,last_name
Craig,David

我的objective是生成一个格式如下的文件:

>>> cat test.csv
time,first_name,last_name
1527661792118,Craig,David

Serde attributes 没有添加附加字段的选项。在上面的示例中,Person 结构不包含 time 值。 time 值仅在将数据写入 CSV 时才需要。

如果您不想向 Person 添加时间戳列,您可以为此创建一个单独的结构,然后将它们连接到一个元组中:

#[derive(Debug, Deserialize, Serialize)]
struct Timestamp {
    time: u64,
}

impl Timestamp {
    fn now() -> Timestamp {
        Timestamp { time: current_ms() }
    }
}

fn main() {
    let person = Person {
        first_name: "Craig".to_string(),
        last_name: "David".to_string(),
    };
    let person_and_time = (Timestamp::now(), person);
    let file_path = std::path::Path::new("test.csv");
    let mut wtr = csv::Writer::from_path(file_path).unwrap();
    wtr.serialize(&person_and_time).unwrap();
}