rust - 如何使用 toml-rs 检查 TOML 中是否存在 key ?

标签 rust

我有一个 TOML 文档,其中某些键可能存在也可能不存在。例如。该文件是有效文件:

foo = "bar"

但这也是有效的:

foo = "bar"
something = "else"

我现在正尝试使用库 toml-rs 在 Rust 中解析此文档.但是,我在文档中找不到任何关于如何查明 key 是否实际存在于我的 TOML 文档中的指导。每当我尝试访问此键时,程序都会出现错误 index not found

我提出了以下简约示例,它表明当我尝试访问不存在的 key 时 Rust 代码立即失败:

use toml::Value;

fn main() {
    let value = "foo = 'bar'".parse::<Value>().unwrap();

    println!("{:?}", value["foo"]);
    println!("{}", "before");
    println!("{:?}", value["foo2"]);
    println!("{}", "after");
}

这导致输出:

String("bar")
before
thread 'main' panicked at 'index not found', src/libcore/option.rs:1034:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

在库的实际代码中我找到了a comment for a function called get指出:

Also returns None if the given key does not exist in the map or the given index is not within the bounds of the array.

但是,我不确定这是否也适用于我的 key 访问。至少在我的测试中它没有。我也无法在代码中找到检查 key 是否存在的函数。

我想一定有什么方法可以查明 TOML 文档中是否存在某个键?

最佳答案

get()而你正在做的是进入图书馆的两条完全不同的路径。此按键访问是 an implementation of Index<_> 如果 key 不存在,会 panic

这就是您在代码中看到的。

做你想做的事情的真正方法确实是使用get() ,这将返回一个 Option ,但首先,我们要解决 toml 的情况。你喂的不是一张 table ,像这样:

use toml::{Value};
use toml::map::Map;

fn main() {
    let value = "foo = 'bar'".parse::<Value>().ok().and_then(|r| match r {
        Value::Table(table) => Some(table),
        _ => None
    }).unwrap_or(Map::new()); // This now contains a HashMap<String, Value>
    println!("{:?}", value.get("foo"));
    println!("{}", "before");
    println!("{:?}", value.get("foo2"));
    println!("{}", "after");
}

关于rust - 如何使用 toml-rs 检查 TOML 中是否存在 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57946845/

相关文章:

rust - 处理传递给过程宏的编译时相关文本文件的正确方法

rust - 使用对比较运算符或函数的引用来比较某些值

recursion - 在获取递归数据结构的所有权时避免部分移动值?

rust - 选择第一个 Some() 选项的惯用方式?

rust - 产生任务时的生命周期错误

std - 使用哪个 std::sync::atomic::Ordering ?

Rust - 单行内的条件变异

vector - 连接字符串向量的向量

rust - 使用serde_cbor在Rust中将Vec <u8>序列化为CBOR字节字符串

rust - 仅按变体比较枚举,不按值比较