Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUST

armanriazi•rust•comparison•generic•associated type

pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;
}
impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        // --snip--
-This syntax seems comparable to that of generics. 

pub trait Iterator<T> {
    fn next(&mut self) -> Option<T>;
}
-A hypothetical definition of the Iterator trait using generics

With associated types, we don’t need to annotate types because we can’t implement a trait on a type multiple times. 
At the First Exampele with the definition that uses associated types, we can only choose what the type of Item will be once, because there can only be one impl Iterator for Counter. 
We don’t have to specify that we want an iterator of u32 values everywhere that we call next on Counter.
 
PREVIOUS NEXT
Tagged: #type
ADD COMMENT
Topic
Name
4+7 =