Hacker News new | ask | show | jobs
by josephg 1063 days ago
Or Rust! Everything that implements the Iterator trait gets access to all of Iterator’s goodies, like map, filter, reduce, etc. Implementing iterator just requires adding a single next(&mut self) -> Option<Item> method on your type.

Lifetimes and async are a massive pain in rust. But the trait system is a work of art.

2 comments

I like Rust's struct + traits approach, because they avoid inheritance and encourage composition. I am sure people have built bad workarounds though to do inheritance anyway.
ruby is closer to what i meant because you can't add methods to rust's iterator, can you? but people add stuff to enumerable all the time
You can!

    trait MyIterHelpers: Iterator {
        fn dance(&self) {
            println!("wheee");
        }
    }
    
    // And tell rust that all Iterators are also MyIterHelpers.
    impl<I: Iterator> MyIterHelpers for I {}
The one caveat is that using it in a different context will need a use crate::MyIterHelpers; line, so the namespace isn't polluted.
neat, i didn't know that was possible