Associated type traits

trait Foo {
type Out;
fn get_value(self) -> Self::Out;
}

These are a better alternative to generic traits due to their ability to declare associated types within the trait, like the Out type in the declaration of Foo in the preceding code. They have a less verbose type signature. The advantage of them is that, in the implementation, they allow us to declare the associated type once and use Self::Out as the return type or parameter type in any of the trait methods or functions. This removes the redundant specification of types, as is the case with generic traits. One of the finest examples of associated type traits is the Iterator trait, which is used for iterating over the values of a custom type. Its documentation can be found at https://doc.rust-lang.org/std/iter/trait.Iterator.html. We'll dig deeper into iterators when we get to Chapter 8,  Advanced Topics.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset