Quick actions

cmd+k|ctrl+k

Navigation

Languages

iterators

Snippet info

Language

Rust

Visibility

public

Author

ilicivan

Created

2018-02-08T16:40:54Z

Updated

2018-02-09T03:07:16Z

struct Counter {
    count: u8,
}

impl Counter {
    fn new() -> Self {
        Self { count: 0 }
    }
}

impl Iterator for Counter {
    type Item = u8;
    fn next(&mut self) -> Option<Self::Item> {
        self.count += 1;
        if self.count < 6 {
            Some(self.count)
        } else {
            None
        }
    }
}

fn main() {
    // using this custom iterator
    let mut c: Counter = Counter::new();
    for el in c.into_iter() {
        println!("c.next: {:?}", el);
    }


    use std::ffi::OsStr;
    // path
    let path = ::std::path::Path::new("C:/Users/JimB/Downloads/Fedora.iso");
    // path iterator
    let mut iterator: std::path::Iter = path.iter();
    // first element
    assert_eq!(iterator.next(), Some(OsStr::new("C:")));
    // other elements, but the first
    for el in iterator {
        println!("it.next: {:?}", el);
    }
    
    
    // into_iter
    use std::collections::BTreeSet;
    let mut favorites = BTreeSet::new();
    
    favorites.insert("Lucy in the Sky With Diamonds".to_string());
    favorites.insert("Liebesträume No. 3".to_string());
    
    let mut it = favorites.into_iter();
    
    assert_eq!(it.next(), Some("Liebesträume No. 3".to_string()));
    assert_eq!(it.next(), Some("Lucy in the Sky With Diamonds".to_string()));
    assert_eq!(it.next(), None);
}

INFO