关于rust-lang:Rust的Blanket-Implements通用实现

8次阅读

共计 1833 个字符,预计需要花费 5 分钟才能阅读完成。

在 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

正文完
 0