Using functions defined in primitive modules

后端 未结 1 1929
傲寒
傲寒 2021-01-28 06:29

I\'d like to make use of this function:

u8::from_str(src: &str) -> Result

I can\'t seem to figure out the syntax to use it. Thi

1条回答
  •  无人共我
    2021-01-28 07:14

    The trick here is that from_str is actually part of the trait FromStr. You need to use that trait, then specify which implementation you want to use:

    use std::str::FromStr;
    
    fn main() {
        match ::from_str("89") {
            // Stuff...
        }
    }
    

    However, this particular concept has a more ergonomic option: parse:

    fn main() {
        match "89".parse::() {
            // Stuff...
        }
    }
    

    And you might be able to remove the :: if something else constrains the type enough for it to be inferred.

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