4 ms·
So basically, Java's generic interfaces are equivalent to Rust's traits with associated types, and Java has no equivalent for a Rust trait with type parameters,
by tsimionescu 2y ago
So basically, Java's generic interfaces are equivalent to Rust's traits with associated types, and Java has no equivalent for a Rust trait with type parameters, at least in terms of this part of the language.
I'm not sure how or if Rust traits can be used as function parameters - can I have a function that takes a parameter of type Iter? Can it take any implementation of Iter than, regardless of what item type that returns? How would I define a function that only accepts iterators that return, say, i32 items?
- AlotOfReading 2y agoYou'd write it as a type parameter with a type bound. There's a couple of different ways to write it, but one example: fn foo<I>(it: I) where I : Iterator<Item = i32> {}
- LegionMammal978 2y ago> can I have a function that takes a parameter of type Iter? fn example<I: Iterator>(iter: I) { ... } // or: fn example<I>(iter: I) where I: Iterator { ... } // or: fn example(iter: impl Iterator) { ... } > Can it take any implementation of Iter than, regardless of what item type that returns? Yes, in the above example. Then, the item type can be referred to as "<I as Iterator>::Item", or "I::Item" for short, unless you use the "impl Trait" syntax. You can also give the item type a name by giving it its own type parameter: fn example<T, I: Iterator<Item = T>>(iter: I) { ... } > How would I define a function that only accepts iterators that return, say, i32 items? fn example<I: Iterator<Item = i32>>(iter: I) { ... } // etc., just write Iterator<Item = i32> in place of Iterator