gpt4 book ai didi

rust - 将 'key exists' 与 'and if its the right type' 解析 toml 结合的惯用方式

转载 作者:行者123 更新时间:2023-12-03 11:47:52 26 4
gpt4 key购买 nike

我正在解析这个

[xxxxx]
drive0={}
drive1={path="xxxx"}
...
有时有路径,有时没有。
我有工作代码,但我仍在尝试学习 Rust 惯用的做事方式。代码:
for i in 0..8 {
let drive_name = format!("drive{}", i);
if dmap.contains_key(&drive_name) {
if let Some(d) = config[drive_name].as_table() {
this.units.push(Rkunit::new(true));
if d.contains_key("path") {
if let Some(path) = d["path"].as_str() {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path)
.unwrap();
this.units[i].file.replace(file);
}
}
} else {
this.units.push(Rkunit::new(false));
}
}
}


我期望
if let Some(path) = d["path"].as_str()
(即没有 if d.contains() 行)
将处理这两种情况 - 即没有“路径”和“路径”不是字符串,但事实并非如此。与 contains_key(drive_name) 相同也。
我尝试了各种猜测的语法,看看我是否可以避免另一个嵌套的 if 并且可以找到一个。
那么有没有更好的方法,或者它是否已经足够好了。欢迎对解析 toml 的任何其他评论。

最佳答案

有人可能认为链接选项更惯用,但更难遵循。

config.get(&driver_name)
.or_else(|| { // no drive, passing None all the way down
this.units.push(Rkunit::new(false));
None
})
.and_then(|drive| { // having a drive, trying to get a path
this.units.push(Rkunit::new(true));
drive.as_table().get("path")
})
.map(|path| { // only having a path, we're doing the thing
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path.as_str()) // as_str is there
.unwrap();
this.units[i].file.replace(file);
});
// also "unused Option" warning, because map returns an Option<()>

关于rust - 将 'key exists' 与 'and if its the right type' 解析 toml 结合的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63714517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com