Traits and Impl
A very powerful feature of Rust that is commonly seen when dealing with generics is that it is possible to tell the compiler that a particular type will provide certain functionality. This is provided by a special feature known as a trait
.
However, to appreciate traits, we first have to look at the impl
keyword (short for implement).
Impl
The impl
keyword works in a very similar way to a function. The structure of an implementation needs to considered as being closer to a static class (in C#) or as a function within a function:
impl MyImpl { fn reference_name (&self) ... }
This would be more for a non-generic type. For generics, the preceding code becomes the following:
impl <T> MyGenericImpl<T> { fn reference_name(&self) ... }
Note that the <T>
is required to tell the compiler that the impl
is for a generic. reference_name
is the name used to access the impl
function. It can be anything you wish.
Note
An example of impl
can be found in 09/impl_example...