在Rust中的实现,您能够扩大实现的类型的性能。实现是应用impl关键字定义的,并且蕴含属于类型实例的函数 或者 属于以后类型实例的函数。

With implementations in Rust, you can extend the functionality of an implementation type. Implementations are defined with the impl keyword and contain functions that belong to an instance of a type, statically, or to an instance that is being implemented.

With blanket implementations you can save writing similar implementations for multiple types.

你能够应用blanket impl 保留对于多种类型类似的实现。


什么是blanket implementations

官网定义:

We can also conditionally implement a trait for any type that implements another trait. Implementations of a trait on any type that satisfies the trait bounds are called _blanket implementations_ and are extensively used in the Rust standard library. For example, the standard library implements the ToString trait on any type that implements the Display trait.

咱们能够有条件地为任何一个实现了另一个Trait的类型实现一个Trait。 为任何一个满足 Trait bound的类型实现一个Trait, 称为通用实现(_blanket implementations_)。 且被宽泛地应用于Rust规范库。 举个例子, 规范库为任何一个实现了Display Trait的类型实现了 ToString Trait。

Blanket implementations leverage Rust’s ability to use generic parameters. They can be used to define shared behavior using traits. This is a great way to remove redundancy in code by reducing the need to repeat the code for different types with similar functionality.
In the code below, we are making a blanket implementation on a _generic type_, T, that implements the Display trait.


Blanket implementations(通用实现)使Rust具备应用模板参数的能力。它们可用于应用Trait来定义共享行为。 最大的用途就是缩小为不同类型的类似性能写反复代码, 以缩小冗余代码。
以下的代码, 咱们为 实现了Display trait的模板参数T 定义了一个通用实现。

impl<T: Display> ToString for T {    // ...}


To elaborate, our generic type, T, is bound to implement Display. Therefore, we use behavior guaranteed by the Display type, to produce a string representation, to our advantage.
具体地说,咱们的模板类型T必须实现Display。因而,咱们利用Display类型保障的行为来产生字符串示意模式,来施展Rust的劣势。

参考


《官网文档》 https://doc.rust-lang.org/book/ch10-02-traits.html#using-trait-bounds-to-conditionally-implement-methods


《Definition: Blanket implementation》 https://www.educative.io/edpresso/definition-blanket-implementation