Cargo.toml
.toml文件解析
👉整个Toml文件其实就是一个大 Table,里面包含了多组键值对,值也可以是一个Table,大概长这样:
Table({
key1 : value1,
key2 : Table({
key3:value3
}),
...
})
举个🌰:
a = "b" #解析之后的数据结构👉"a": String("b",),
i = 1 #解析之后的数据结构👉"i": Integer(1,),
[package] #👉"package": Table({ "name": String("study-toml",),...}),
name = "study-toml"
version = "0.1.0"
edition = "2021"
[dependencies]
toml = "0.8.13"
[my_string]
hello_world = "hello world"
读取整个toml文件并打印:
程序:
// main.rs
extern crate toml;
use std::fs;
use toml::Value;
fn main() {
let toml_content = fs::read_to_string("Cargo.toml").expect("Unable to read file");
let parsed_toml: Value = toml::from_str(&toml_content).expect("Unable to parse TOML");
println!("{:#?}", parsed_toml);
// let toml_version = &parsed_toml["my_string"]["hello_world"];
// println!("{:?}", toml_version);
}
⚠️需在配置文件 Cargo.toml 中 添加依赖:
[dependencies]
toml = “0.8.13”然后
cargo build
,再cargo run
。
输出:
Table(
{
"a": String(
"b",
),
"dependencies": Table(
{
"toml": String(
"0.8.13",
),
},
),
"i": Integer(
1,
),
"my_string": Table(
{
"hello_world": String(
"hello world",
),
},
),
"package": Table(
{
"edition": String(
"2021",
),
"name": String(
"study-toml",
),
"version": String(
"0.1.0",
),
},
),
},
)