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

分类: 计算机技术
推荐阅读:
Rust爬取网页上的所有链接 要在Rust中爬取网页上的所有链接,可以使用一些Rust的库,例如reqwest和scraper。
Python breakpoint()函数详细教程 brekpoint()函数是python3.7版本新增的一个内置函数;该函数会在调用时使程序进入调试器中;
Rust中的 if 表达式 if表达式允许根据条件的不同而执行不同的代码分支,如果条件满足,则运行某段代码,如果条件不满足则不运行这段代码;
使用MATLAB求函数的导数 要使用 MATLAB 求一个函数的导数,可以使用 "diff" 函数。这个函数需要两个输入参数:要求导的函数和自变量。
使用Python求取前n个自然数的总和 给一个自然数n,使用Python求取前n个自然数的总和;
C程序判断一个数是否为质数,并打印100以内的质数 在本文中,我们将使用C语言来判断一个整数是否为质数,并打印100以内的所有质数;