美文网首页
关于Rust读取自定义toml文件

关于Rust读取自定义toml文件

作者: 包牙齿 | 来源:发表于2018-03-15 03:10 被阅读436次

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

  • 思路,关于自定义的toml文件应该有一定配置规则,不清楚或者不了解toml文件配置的点击这个链接

  • 知道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"
    
  • 如果有了类似配置后,大致是一下几步:

    • ①我们只需要读取该文件到对应内存
    • ②然后构造对应数据结构
    • ③序列化

    ok,我们下面来试试吧。

准备前

定义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

相关文章

网友评论

      本文标题:关于Rust读取自定义toml文件

      本文链接:https://www.haomeiwen.com/subject/mzlcqftx.html