implement an external trait for a local type.This is common in larger programs that use polymorphic abstractions. implement a local trait for a local type.State that the following combinations of “local” (this crate) and “external” (other crates 5) are legal: (described briefly towards the end of this section of the Rust book) They are a conscious choice on the part of Rust authors,Īnd they were decided upon in an effort to keep the type system coherent.Ĭoherence isn’t an everyday topic in Rust,īut it becomes important when working with traits and types that cross package boundaries. Indeed, this technique has some limitations. It is only right to mention what they cannot do. So far, we have seen what extension traits are capable of. Reading this section is not necessary to use extension traits. Is left as an exercise for the reader :) Extra credit bonus explanation Replacing Box with an idiomatic error enum Use ext :: rust :: OptionMutExt // assuming you put it in ext/rust.rs //. Here’s the appropriate extension trait 4: The goal is to make it more convenient to operate on mutable Optionsīy allowing to easily replace an existing value with another one 3. We’re going to add two new methods to Rust’s standard Option type. I’m sure you are keen on seeing some examples! Broadening your Options Once that’s done, it can proceed to use the new methods is if they were there to begin with.
#Hyper extension code#
The calling code needs to import your new trait in addition to the external type. Define a trait with signatures of all the methods you want to add.In order to “patch” some new method(s) into an external type you will need to: It involves a certain degree of boilerplate and duplication. The crux of this technique is really simple. types from the current crate if additional methods only make sense in certain scenarios.types imported from third-party libraries.Or anything else inside the std namespace Rust standard library types, like Result, String,.That we don’t otherwise control (or don’t want to modify). We can use the extension trait pattern if we want to have additional methods in a type Let’s have a look at how they are commonly implemented. Personally, I’ve taken to calling it extension traits. I’m not sure if this pattern has an official or widely accepted name. Utilize it very successfully to add new, useful methods to the language standard types. Like itertools or unicode-normalization. Which involves third-party types and user-defined traits. In this post, I’m going to describe a certain design pattern in Rust That it permits extension methods solely as a side effect of its core building block: traits.
The curious thing about Rust‘s type system is That’s assuming you have imported both the original classĪs well as the module in which the extension method is defined.