Search code examples
rustiterator

Is it possible to get iterator value without switch to the next position:


In C++ I can get current value of iterator many times

int main() {
    std::string s = "abcd";
    auto iter = s.begin();
    std::cout << *iter << std::endl; // a
    std::cout << *iter << std::endl; // a
}

Can I do the same in Rust? Is it possible to get iterator value without switch to the next position:

fn main() {
    let mut s = String::from("abcd");
    let mut iter = s.chars();
    println!("{:?}", iter.next()); // get Some(a) and switch to the next position    
}

Solution

  • My solution:

    fn main() {
        let mut s = String::from("abcd");
        let mut iter = s.chars().peekable();
        println!("{:?}", iter.peek()); // get Some(a)    
        println!("{:?}", iter.peek()); // get Some(a)    
    }