我看过type一些Rust示例中使用的关键字,但我从未见过它的解释.我看到它如何使用的几个例子:
impl Add<Foo> for Bar {
    type Output = BarFoo;
    // omitted
}
Run Code Online (Sandbox Code Playgroud)
而这,取自参考:
type T = HashMap<i32,String>; // Type arguments used in a type expression
let  x = id::<i32>(10);       // Type arguments used in a call expression
Run Code Online (Sandbox Code Playgroud)
有人可以解释这个关键字的作用吗?我在Rust by Example或Rust书中找不到它.
小智 25
一个简单的type Foo = Bar;外部impl定义了一个类型别名,并在本书中有记载.有一个通用版本,type Foo<T> = ...但如果您了解泛型,那么这是一个明显的扩展.
type在一个impl定义一个相关的类型.它们在The Book中有记载,但我已经写了一个简短的摘要,所以你也得到了它:
当你有类似的特征时Add,你不仅要抽象可以添加什么类型的东西,还要抽象它们的总和类型.添加整数会产生整数,添加浮点会导致浮点数.但是你不希望结果类型Add成为in 的参数,因为Add<ThingToAdd, ResultType>我将在这里略过.
因此,该特征带有与之相关的类型impl.给定Add例如任何实现,impl Add<Foo> for Bar已经确定了相加结果的类型.这是在这样的特征中声明的:
trait Add<Rhs> {
    type Result;
    // ...
}
Run Code Online (Sandbox Code Playgroud)
然后所有实现都定义了结果的类型:
impl Add<Foo> for Bar {
    type Result = BarPlusFoo;
    // ...
}
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           6088 次  |  
        
|   最近记录:  |