关于Rust读取自定义toml文件

2018-03-15  本文已影响436人  包牙齿

参考链接:https://github.com/baoyachi/read-toml

准备前

定义toml文件

    [[ip_config]]
    name="CN"
    ip="192.168.1.1"
    port="11"

    [[ip_config]]
    name="TW"
    ip="192.168.2.2"
    port="22"

    [[ip_config]]
    name="JP"
    ip="192.168.3.3"
    port="33"

构造数据结构

    struct IpConfig {
        name: Option<String>,
        ip: Option<String>,
        port: Option<String>
    }
    
    struct Conf
    {
        ip_config: Option<Vec<IpConfig>>
    }
    

读取文件到内存,序列化

#[macro_use]
extern crate serde_derive;
extern crate toml;

use std::fs::File;
use std::io::prelude::*;

#[derive(Deserialize)]
#[derive(Debug)]
struct IpConfig {
    name: Option<String>,
    ip: Option<String>,
    port: Option<String>,
}

#[derive(Deserialize)]
#[derive(Debug)]
struct Conf
{
    ip_config: Option<Vec<IpConfig>>
}

fn main() {
    let file_path = "config.toml";
    let mut file = match File::open(file_path) {
        Ok(f) => f,
        Err(e) => panic!("no such file {} exception:{}", file_path, e)
    };
    let mut str_val = String::new();
    match file.read_to_string(&mut str_val) {
        Ok(s) => s
        ,
        Err(e) => panic!("Error Reading file: {}", e)
    };
    let config: Conf = toml::from_str(&str_val).unwrap();

    for x in config.ip_config.unwrap() {
        println!("{:?}", x);
    }
}

ok,到此,自定义toml文件内容就加载到 config 中来了,打印出数据分别是

IpConfig { name: Some("CN"), ip: Some("192.168.1.1"), port: Some("11") }
IpConfig { name: Some("TW"), ip: Some("192.168.2.2"), port: Some("22") }
IpConfig { name: Some("JP"), ip: Some("192.168.3.3"), port: Some("33") }

项目链接地址:https://github.com/baoyachi/read-toml

上一篇下一篇

猜你喜欢

热点阅读