Pass None into a function that accepts Option

后端 未结 1 837
轮回少年
轮回少年 2020-12-07 03:53

rust-ini has a function:

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

        
1条回答
  •  天涯浪人
    2020-12-07 04:10

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

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

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

    let section = ifo_cfg.section::(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 :: 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 :: 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.

    0 讨论(0)
提交回复
热议问题