Rust解析TOML,结构体序列化和反序列化

在Rust中,可以使用标准库中的toml模块来解析和生成TOML格式的数据;serdetoml模块集成,可以将TOML字符串解析为任意Rust结构体,或将Rust结构体序列化为TOML格式的字符串。

TOML是一种简单、符合人体工程学且可读的配置格式;Rust的包管理器cargo就使用TOML格式;

以下为Cargo.toml文件的一个例子:

[package]
name = "a1"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
toml = "0.7.3"

添加依赖

要使用tomlserde,需添加依赖,编辑Cargo.toml文件,添加以下内容:

[dependencies]
serde = { version = "1.0", features = ["derive"] }
toml = "0.7.3"

使用toml模块

toml模块提供一个代表TOML表的结构体toml::Table,可以使用它来访问和操作TOML格式的数据;

pub type Table = Map<String, Value>;

其中,Value表示toml::Value,是一个代表TOML值的枚举:

pub enum Value {
    String(String),
    Integer(i64),
    Float(f64),
    Boolean(bool),
    Datetime(Datetime),
    Array(Array),
    Table(Table),
}

解析TOML文档

解析TOML文档最简单的方法是通过Table类型:

use toml::Table;

fn main(){

    let toml_text = r#"
        a = "perfcode.com"
        b = true
        [others]
        c = 3
    "#;

    let value = toml_text.parse::<Table>().unwrap();
    
    println!("{}\n{}\n{}",
        value["a"].as_str().unwrap(),
        value["b"].as_bool().unwrap(),
        value["others"]["c"].as_integer().unwrap(),
    );
}

程序运行结果

perfcode.com
true
3

要获得toml::Table的详细用法,请访问 Rust toml::Table详细用法

使用toml::from_str函数解析

toml模块提供一个toml::from_str函数可将TOML文档转换成toml::Table类型;修改前一个例子:

use toml::Table;

fn main(){

    let toml_text = r#"
        a = "perfcode.com"
        b = true
        [others]
        c = 3
    "#;

    let value:Table = toml::from_str(&toml_text).unwrap();

    println!("{}\n{}\n{}",
        value["a"].as_str().unwrap(),
        value["b"].as_bool().unwrap(),
        value["others"]["c"].as_integer().unwrap(),
    );
}

使用toml::to_string函数转换成字符串

可以使用toml::to_string函数,将toml::Table类型转换成TOML字符串:

use toml::Table;

fn main(){

    let toml_text = r#"
        a = "perfcode.com"
    "#;

    let mut value:Table = toml::from_str(&toml_text).unwrap();

    value.insert("b".to_string(),toml::Value::String("www.perfcode.com".to_string()));

    let new_toml = toml::to_string(&value).unwrap();

    println!("{}",new_toml);

}

程序运行结果

a = "perfcode.com"
b = "www.perfcode.com"

对结构体序列化和反序列化

一个TOML反序列化的例子:

use serde::{Deserialize,Serialize};

#[derive(Deserialize,Serialize)]
struct Config {
    ip: String,
    port: u16,
    others: Others
}

#[derive(Deserialize,Serialize)]
struct Others {
    salt: String,
    use_whitelist: bool,
}

fn main(){

    let tom_text = r#"
        ip = "127.0.0.1"
        port = 80
        [others]
        salt = "xxxxxx"
        use_whitelist = false
    "#;

    let config:Config = toml::from_str(tom_text).unwrap();

    println!("ip: {}\nport: {}\nsalt: {}\nuse_whitelist: {}",
        config.ip,
        config.port,
        config.others.salt,
        config.others.use_whitelist
    );
}

程序运行结果

ip: 127.0.0.1
port: 80
salt: xxxxxx
use_whitelist: false

一个TOML序列化的例子:

use serde::{Deserialize,Serialize};

#[derive(Deserialize,Serialize)]
struct Config {
    ip: String,
    port: u16,
    others: Others
}

#[derive(Deserialize,Serialize)]
struct Others {
    salt: String,
    use_whitelist: bool,
}

fn main(){

    // 序列化
    let new_config = Config {
        ip: "0.0.0.0".to_string(),
        port: 80,
        others: Others {
            salt: "ssssssssss".to_string(),
            use_whitelist: true
        }
    };
    let new_toml = toml::to_string(&new_config).unwrap();
    
    println!("{}",new_toml);
    
}

程序运行结果

ip = "0.0.0.0"
port = 80

[others]
salt = "ssssssssss"
use_whitelist = true

原创内容,如需转载,请注明出处;

本文地址: https://www.perfcode.com/rust-serde/serde-toml.html

分类: 计算机技术
推荐阅读:
使用pyi-set_version为PyInstaller打包出来的程序附加版本信息 本文将讲述如何使用 pyi-grab_version 获取版本信息的模板文件,以及使用 pyi-set_version 为打包好的程序附加版本信息。
使用pyi-bindepend工具查看EXE文件的依赖库 pyi-bindepend.exe工具是PyInstaller的一个附属工具,其功能是获得EXE文件运行时需要的依赖文件,当丢失这些文件时,程序无法运行。
C程序计算二阶行列式的值 本文将使用C语言编写程序计算二阶行列式的值;程序通过定义一个2*2数组用于存储输入的二阶行列式;再通过前文的公式计算出二阶行列式的值;
将PySide6升级到最新版本 由于PySide6还在不断完善阶段,每隔一段时间我们就需要将PySide6升级到最新版本以使用更完善的功能;不论在Windows、Linux、还是macOS系统下,都只需要运行以下命令即可完成升级:
使用PySide6创建窗口以及各类窗口的区别 在本文中,你将了解Qt的窗口,以及QMainWindow、QWidget、QDialog之间的区别和在PySide6中的使用方法;
Rust获取代码的运行时间 在 Rust 中,你可以使用 std::time::Instant 模块来测量代码的运行时间。以下是一个简单的示例代码,演示如何在 Rust 中测量代码的运行时间: