News for hackers. Stuff that matters.
Re:Fear Not the Association of Types by bombela on Sunday August 18, 2024 @03:02PM (#41284523)
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
Re:Fear Not the Association of Types by tsimionescu on Sunday August 18, 2024 @03:32PM (#41284782)
I 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.

Re:Fear Not the Association of Types by tadfisher on Sunday August 18, 2024 @04:16PM (#41285100)
Java 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).