Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass None into a function that accepts Option

Tags:

rust

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?

like image 637
fghj Avatar asked Jun 17 '16 16:06

fghj


People also ask

How do you pass nothing to a function in Python?

In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing.

Can you pass None as argument in Python?

None is often used as a default argument value in Python because it allows us to call the function without providing a value for an argument that isn't required on each function invocation. None is especially useful for list and dict arguments.

How do you pass an optional parameter to a function in Python?

A type of argument with a default value is a Python optional parameter. A function definition's assignment operator or the Python **kwargs statement can be used to assign an optional argument. Positional and optional arguments are the two sorts of arguments that a Python function can take.


1 Answers

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.

like image 91
kennytm Avatar answered Nov 10 '22 10:11

kennytm