在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.
With blanket implementations you can save writing similar implementations for multiple types.
你能夠使用blanket impl 保留對於多種類型類似的實現。
函數
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 theToString
trait on any type that implements theDisplay
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