在Rust中使用ini配置文件

一、概述

INI文件是一种无固定标准格式的配置文件。它以简单的文字与简单的结构组成,常常使用在Windows操作系统上,许多程序也会采用INI文件作为配置文件使用。Windows操作系统后来以注册表的形式取代INI档。但是INI还是流传到现在。
rust-ini是一个在Rust中使用ini配置文件的库。INI文件是简单的文本文件,其基本结构由“sections”和“properties”组成。

二、使用操作

在Cargo.toml文件中加入依赖库:

[dependencies]
rust-ini = "0.21"

我们演示使用该库来操作INI配置文件。分为创建INI配置文件和读取配置文件。

1.创建INI配置文件

extern crate ini;
use ini::Ini;

fn main() {
    let mut conf = Ini::new();
    conf.with_section(None::<String>)
        .set("encoding", "utf-8");
    conf.with_section(Some("User"))
        .set("given_name", "Tommy")
        .set("family_name", "Green")
        .set("unicode", "Raspberry树莓");
    conf.with_section(Some("Book"))
        .set("name", "Rust cool");
    conf.write_to_file("conf.ini").unwrap();
}

运行程序后,会生成conf.ini配置文件,配置文件内容如下:

encoding=utf-8

[User]
given_name=Tommy
family_name=Green
unicode=Raspberry\x6811\x8393

[Book]
name=Rust cool

2.读取INI配置文件


use ini::Ini;

fn main() {
    let conf = Ini::load_from_file("conf.ini").unwrap();

    let section = conf.section(Some("User")).unwrap();
    let tommy = section.get("given_name").unwrap();
    let green = section.get("family_name").unwrap();

    println!("{:?} {:?}", tommy, green);

    // iterating
    for (sec, prop) in &conf {
        println!("Section: {:?}", sec);
        for (key, value) in prop.iter() {
            println!("{:?}:{:?}", key, value);
        }
    }
}

这个库非常的简单,想查看更多内容,请浏览Github:https://github.com/zonyitoo/rust-ini

相关推荐

  1. Rust使用ini配置文件

    2024-04-21 19:42:04       16 阅读
  2. rust - 使用serde_yaml读取配置文件

    2024-04-21 19:42:04       18 阅读
  3. IDEA使用.env文件配置信息

    2024-04-21 19:42:04       20 阅读
  4. pytest.ini配置文件

    2024-04-21 19:42:04       13 阅读
  5. pytest框架的pytest.ini配置文件

    2024-04-21 19:42:04       9 阅读
  6. 深入理解pytest.ini文件配置使用

    2024-04-21 19:42:04       40 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-21 19:42:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-21 19:42:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-21 19:42:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-21 19:42:04       20 阅读

热门阅读

  1. Rust开发笔记 | Rust的交互式Shell

    2024-04-21 19:42:04       14 阅读
  2. NVIC简介

    2024-04-21 19:42:04       13 阅读
  3. Python与设计模式之适配器的使用方法

    2024-04-21 19:42:04       14 阅读
  4. 三七互娱,oppo,快手25届暑期实习内推

    2024-04-21 19:42:04       16 阅读
  5. SQLSERVER对等发布问题处理

    2024-04-21 19:42:04       12 阅读
  6. 工作中常用到的一些sql脚本

    2024-04-21 19:42:04       15 阅读
  7. 【QT教程】QML音视频效果实现

    2024-04-21 19:42:04       13 阅读
  8. Debian

    Debian

    2024-04-21 19:42:04      11 阅读