Rust的Blanket Implements(通用实现)

在Rust中的实现,您能够扩展实现的类型的功能。实现是使用impl关键字定义的,而且包含属于类型实例的函数 或者 属于当前类型实例的函数。html

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.

image.png

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。 spa

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 定义了一个通用实现。code

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的优点。cdn

参考


《官方文档》 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


htm

相关文章
相关标签/搜索