Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 views
in Technique[技术] by (71.8m points)

rust - Pass None into a function that accepts Option

rust-ini has a function:

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

I want to read a file without sections, so I call it like this:

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();

But it gives a compile error:

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

I can fix it like this:

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

How can fix this without the additional line with none?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could specify the type of the T in the type Option<T> for this None with:

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

Alternatively, you could specify the type S of the method section:

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

You can also look up E0282's explanation, although it might not really answer your question at this time :)


The syntax ::<T,U,V> is sometimes called the turbofish. Some very generic methods like String::parse() and Iterator::collect() can return almost anything, and type inference does not have enough information to find the actual type. The ::<T,U,V> allow the human to tell the compiler what generic parameter should be substituted. From parse()'s reference:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...