What does creating an instance of Rust with underline mean?

When working with serde_json to read json documents, I wrote the following line of code to get the result of expanding the return value serde_json::from_str:

fn get_json_content(content_s: &str) -> Option<Value> {
    let ms: String = serde_json::from_str(content_s).unwrap; // <--

    match serde_json::from_str(content_s) {
        Ok(some_value) => Some(some_value),
        Err(_) => None
    }
}

As you can see, I forgot ()at the end of the call unwrap, which led to the following error:

Error

: tried to accept the method value unwrapby typecore::result::Result<_, serde_json::error::Error>

let ms: String = serde_json::from_str(content_s).unwrap;

But when I looked at this a little further, what seemed strange to me was:

core::result::Result<_, serde_json::error::Error>

I understand what underscore means in the context of compliance, but to create a generic instance? So what does that mean? I could not find the answers in the Rust book, links, or web searches.

+4
source share
1 answer

. , .

, . :

pub fn main() {
    let letters: Vec<_> = vec!["a", "b", "c"]; // Vec<&str>
}

, turbofish operator:

fn main() {
    let bar = [1, 2, 3];
    let foos = bar.iter()
                  .map(|x| format!("{}", x))
                  .collect::<Vec<String>>(); // <-- the turbofish
}

fn main() {
    let bar = [1, 2, 3];
    let foos: Vec<_> = bar // <-- specify a type and use '_' to make the compiler
                           //     figure the element type out
            .iter()
            .map(|x| format!("{}", x))
            .collect(); // <-- no more turbofish
}
+4

All Articles