Using functions defined in primitive modules

2020-05-03 12:46发布

I'd like to make use of this function:

u8::from_str(src: &str) -> Result<u8, ParseIntError>

I can't seem to figure out the syntax to use it. This is what I am currently trying

use std::u8;

match u8::from_str("89") {
    // Stuff...
}

I receive the following error:

error: unresolved name `u8::from_str`

What is the proper way to use functions that are defined in primitive modules?

Thanks in advance for any help!

标签: rust
1条回答
祖国的老花朵
2楼-- · 2020-05-03 13:07

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 <u8 as FromStr>::from_str("89") {
        // Stuff...
    }
}

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

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

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

查看更多
登录 后发表回答