3 ms·
Traits can have associated types. trait Foo { type Bar; } Until now, those types had to be concrete, as in the above example. You can implemen
by stouset 4y ago
Traits can have associated types.
trait Foo {
type Bar;
}
Until now, those types had to be concrete, as in the above example. You can implement Foo with `Bar = u32` and `Bar = String` and even `Bar = Vec<bool>`.
trait Foo {
type Bar<T>;
}
That `Bar` type above can now be generic over some other type `T` so you can implement it for `Bar<T> = Vec<T>`, `Bar<T> = Result<T>`, `Bar<T> = Option<T>`, and any other generic type. That's it. That's the whole thing. Use it if it's useful to you.
If you've never needed to write a trait that incorporated an associated type (.AT) which needed to be generic (G..), then this won't mean much to you and that's fine. But you might be using libraries that could be somewhat more ergonomic if they were able to use this feature. The good news is that now that it's been released to stable, a future version of that library can be written more ergonomically.
- flippinburgers 4y agoIs that what this is all about? I feel like the examples people give are nowhere near this simple.
- stouset 4y agoYep. People are trying to show how you might use it in practice, which is useful. But I think people should start with the above. If you’ve ever used associated types, this is the sort of thing you would probably expect would be possible even if you never needed to do it. Now it’s possible.