用下划线实例化Rust泛型是什么意思? [英] What does it mean to instantiate a Rust generic with an underscore?

查看:269
本文介绍了用下划线实例化Rust泛型是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用serde_json读取json文档时,我编写了以下代码行来获取展开serde_json::from_str的返回值的结果:

While working with serde_json for reading json documents, I wrote the following line of code to obtain the result of unwrapping the return value of 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
    }
}

如您所见,在对unwrap的调用结束时,我忘记了(),这导致了以下错误:

As you can see, I forgot the () on the end of the call to unwrap, which resulted in the following error:

错误:尝试采用方法的价值 unwrap(类型为core::result::Result<_, serde_json::error::Error>

error: attempted to take value of method unwrap on type core::result::Result<_, serde_json::error::Error>

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

但是当我进一步研究时,让我感到奇怪的是:

But when I looked at this a bit further, the thing that struck me as odd was:

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

我了解下划线在匹配上下文中的含义,但是要实例化泛型?那么这是什么意思?我在Rust书,参考书或网络搜索中找不到任何答案.

I understand what underscore means in a match context, but to instantiate a generic? So what does this mean? I couldn't find any answers in the Rust book, or reference, or a web search.

推荐答案

它是一个占位符.在这种情况下,这意味着编译器没有足够的信息来推断类型.

It's a placeholder. In this context, it means that there isn't enough information for the compiler to infer a type.

您可以在代码中使用它来使编译器为您推断类型.例如:

You can use this in your code to make the compiler infer the type for you. For example:

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

这特别方便,因为在许多情况下,您可以避免使用:

This is particularly handy because in many cases you can avoid using the "turbofish operator":

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

vs

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
}

这篇关于用下划线实例化Rust泛型是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆