0

APerson有一个first_name和一个last_nametime将实例写入 CSV 时,如何将导出添加Person到 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

我的目标是生成一个格式为:

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

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

4

1 回答 1

4

如果您不想将时间戳列添加到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();
}
于 2018-05-30T10:15:21.350 回答