3 ms·
Associated type: pub trait Iterator { type Item; [...] } vs generic type: pub trait Iterator<Item> {} The associated type versio
by bombela 2y ago
Associated type:
pub trait Iterator {
type Item;
[...]
}
vs generic type:
pub trait Iterator<Item> {}
The associated type version can only be implemented once per MyType.
impl Iterator for MyType {
type Item = i32;
}
The generic version can be implemented multiple times. For example:
impl Iterator<String> for MyType
impl Iterator<i32> for MyType
https://doc.rust-lang.org/book/ch19-03-advanced-traits.html https://doc.rust-lang.org/book/ch19-03-advanced-traits.html
- tsimionescu 2y agoI understand that part. But the comparison with Java is still bizarre, or perhaps just wrong. Java has nothing similar to this: impl Iterator for MyType { type Item = i32; } If you defined Iterator like this: interface Iterator { interface Item{} public Item next(); ... } Then Iterator.Item is the same type for all implementations, each implementation doesn't get to define its own type. Furthermore, a Java type can't implement both Iterator<Integer> and Iterator<String>: it has to implement a single one. So Java's Iterator<T> is in almost all ways equivalent to Rust's Iter, with its one associated type, and not to a Rust BadIter<T>. And this has nothing to do with how methods are dispatched, it has everything to do with the semantics of their respective type systems.
- tadfisher 2y agoJava has a pattern that is a superset of this, which is the self-recursive generic type: interface Foo<T extends Foo<T>> class Bar implements Foo<Bar> This is used to implement associated-type and Self-type behavior, at the expense of boilerplate. You can have multiple levels of associated types, though, which is murderous on the pinkies (or whatever finger types the angle bracket keys in your layout).