簡體   English   中英

如何從Rust創建TOML文件?

[英]How to create a TOML file from Rust?

我已經將所有數據收集到矢量中,並且需要使用該數據創建一個TOML文件。 我已經成功創建並打開文件:

let mut file = try!(File::create("servers.toml"));

我的vector<(string,(string, u32))>包含以下數據,在TOML中應如下所示。

[server.A]
Ipaddr="192.168.4.1"
Port no=4476

[server.B]
......

我有很多數據需要用TOML編寫,並且我知道TOML是一個文本文件。 編碼器如何使用?

這使用TOML板條箱進行結構和序列化。 主要好處是應該適當地轉義值。

use std::fs;
use toml::{map::Map, Value}; // 0.5.1

fn to_toml(v: Vec<(String, (String, u32))>) -> Value {
    let mut servers = Map::new();
    for (name, (ip_addr, port)) in v {
        let mut server = Map::new();
        server.insert("Ipaddr".into(), Value::String(ip_addr));
        server.insert("Port no".into(), Value::Integer(port as i64));
        servers.insert(name, Value::Table(server));
    }

    let mut map = Map::new();
    map.insert("server".into(), Value::Table(servers));
    Value::Table(map)
}

fn main() {
    let v = vec![
        ("A".into(), ("192.168.4.1".into(), 4476)),
        ("B".into(), ("192.168.4.8".into(), 1234)),
    ];

    let toml_string = toml::to_string(&to_toml(v)).expect("Could not encode TOML value");
    println!("{}", toml_string);

    fs::write("servers.toml", toml_string).expect("Could not write to file!");
}

您還可以將其與Serde的自動序列化和反序列化一起使用,以避免處理底層細節:

use serde::Serialize; // 1.0.91
use std::{collections::BTreeMap, fs};
use toml; // 0.5.1

#[derive(Debug, Default, Serialize)]
struct Servers<'a> {
    servers: BTreeMap<&'a str, Server<'a>>,
}

#[derive(Debug, Serialize)]
struct Server<'a> {
    #[serde(rename = "Ipaddr")]
    ip_addr: &'a str,

    #[serde(rename = "Port no")]
    port_no: i64,
}

fn main() {
    let mut file = Servers::default();
    file.servers.insert(
        "A",
        Server {
            ip_addr: "192.168.4.1",
            port_no: 4476,
        },
    );
    file.servers.insert(
        "B",
        Server {
            ip_addr: "192.168.4.8",
            port_no: 1234,
        },
    );

    let toml_string = toml::to_string(&file).expect("Could not encode TOML value");
    println!("{}", toml_string);
    fs::write("servers.toml", toml_string).expect("Could not write to file!");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM