本文介绍了语法是什么:`instance.method::<SomeThing>()`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 byteorder 中阅读了以下语法:

I read the below syntax from byteorder:

rdr.read_u16::<BigEndian>()

我找不到任何解释语法 instance.method::<SomeThing>()

I can't find any documentation which explains the syntax instance.method::<SomeThing>()

推荐答案

这种构造称为 turbofish.如果你搜索这个语句,你会发现它的定义和用法.

This construct is called turbofish. If you search for this statement, you will discover its definition and its usage.

虽然The Rust Programming Language的第一版已经过时,但我觉得这个特定部分第二本书.

Although the first edition of The Rust Programming Language is outdated, I feel that this particular section is better than in the second book.

引用第二版:

path::, method::
指定表达式中泛型类型、函数或方法的参数;通常被称为turbofish(例如,"42".parse::<i32>())

您可以在编译器无法推导出类型参数的任何情况下使用它,例如

You can use it in any kind of situation where the compiler is not able to deduce the type parameter, e.g.

fn main () {
    let a = (0..255).sum();
    let b = (0..255).sum::<u32>();
    let c: u32 = (0..255).sum();
}

a 不起作用,因为它无法推断变量类型.
b 确实有效,因为我们直接使用 turbofish 语法指定了类型参数.
c 确实有效,因为我们直接指定了 c 的类型.

a does not work because it cannot deduce the variable type.
b does work because we specify the type parameter directly with the turbofish syntax.
c does work because we specify the type of c directly.

这篇关于语法是什么:`instance.method::<SomeThing>()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 15:32