gpt4 book ai didi

rust - 将 None 传递给接受 Option 的函数

转载 作者:行者123 更新时间:2023-11-29 08:03:07 26 4
gpt4 key购买 nike

rust-ini有一个功能:

pub fn section<'a, S>(&'a self, name: Option<S>) -> Option<&'a Properties>
where S: Into<String>

我想读取一个没有节的文件,所以我这样调用它:

let ifo_cfg = match Ini::load_from_file("conf.ini") {
Result::Ok(cfg) => cfg,
Result::Err(err) => return Result::Err(err.msg),
};
let section = ifo_cfg.section(None).unwrap();

但是它给出了一个编译错误:

unable to infer enough type information about _; type annotations or generic parameter binding required [E0282]

我可以这样解决:

let none: Option<String> = None;
let section = ifo_cfg.section(none).unwrap();

如何在不使用 none 的附加行的情况下解决这个问题?

最佳答案

您可以指定 T 的类型在类型 Option<T>为此 None与:

let section = ifo_cfg.section(None::<String>).unwrap();
// ^^^^^^^^^^ forces the type to be Option<String>

或者,您可以指定类型 S方法的section :

let section = ifo_cfg.section::<String>(None).unwrap();
// ^^^^^^^^^^ forces S = String

你也可以查E0282's explanation , 尽管此时它可能无法真正回答您的问题:)


语法 ::<T,U,V>有时称为 the turbofish .一些非常通用的方法,如 String::parse()Iterator::collect()几乎可以返回任何东西,类型推断没有足够的信息来找到实际类型。 ::<T,U,V>允许人们告诉编译器应该替换什么通用参数。来自 parse()引用资料:

Because parse() is so general, it can cause problems with type inference. As such, parse() is one of the few times you'll see the syntax affectionately known as the 'turbofish': ::<>. This helps the inference algorithm understand specifically which type you're trying to parse into.

关于rust - 将 None 传递给接受 Option 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37886379/

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