Cargo.toml
.toml文件解析
读(read) toml文件中的指定内容
👉读取 Cargo.toml
文件中的 [my_string]
段中 key 为 hello_world
的值:
# Cargo.toml
a = "b"
i = 1
[dependencies]
toml = "0.8.13"
[my_string]
hello_world = "hello world"
[package]
edition = "2021"
name = "study-toml"
version = "0.1.0"
👇代码:
// project-boot-dir/src/main.rs
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");
// 1.打印整个toml文件,即一个big Table
// println!("{:#?}", parsed_toml);
// 2.读toml文件下my_string段的下 key为 hello_world 的 value值(会直接panic)
// let toml_version = &parsed_toml["my_string"]["hello_world"];
// 2.1避免直接panic的写法
match parsed_toml.get("my_string").and_then(|ms| ms.get("hello_world")){
Some(value) => {println!("{:?}", value);},
None => {
println!("未找到值: {}", "hello_world");
}
}
}
输出:
String("hello world")
写/改(write) toml文件中内容
代码👇
// project-boot-dir/src/main.rs
mod write;
// use std::fs;
// use toml::Value;
use write::*;
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");
// // 1.打印整个toml文件,即一个big Table
// // println!("{:#?}", parsed_toml);
// // 2.读toml文件下my_string段的下 key为 hello_world 的 value值(会直接panic)
// // let toml_version = &parsed_toml["my_string"]["hello_world"];
// // 2.1避免直接panic的写法
// match parsed_toml.get("my_string").and_then(|ms| ms.get("hello_world")){
// Some(value) => {println!("{:?}", value);},
// None => {
// println!("未找到值: {}", "hello_world");
// }
// }
// 3.修改toml文件中的指定值
let my_string = "my_string".to_string();
let hello_world = "hello_world".to_string();
match toml_modified(my_string, hello_world) {
Ok(()) => println!("Ok"),
Err(e) => println!("{e}"),
}
}
// project-boot-dir/src/write.rs
use std::fs;
use toml::Value;
// 修改toml文件中的指定 段+key 的值,如[my_string]段的hello_world对应的key
pub fn toml_modified(table: String, key: String) -> Result<(), Box<dyn std::error::Error>>{
let fs = fs::read_to_string("Cargo.toml")?;
// 解析 TOML 数据为 Value
let mut value: Value = toml::from_str(&fs)?;
// 获取指定部分的可变引用
if let Some(my_string) = value.get_mut(table).and_then(Value::as_table_mut) {
my_string.insert(key, Value::String("new value".to_string()));
}
// println!("{:#?}", value);
std::fs::write("Cargo.toml",toml::to_string(&value)?)?;
Ok(())
}
输出:
Ok
查看Cargo.toml
文件
a = "b"
i = 1
[dependencies]
toml = "0.8.13"
[my_string]
hello_world = "new value" #⚠️已修改
[package]
edition = "2021"
name = "study-toml"
version = "0.1.0"