Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator's next returns Some(&1). Why's that?

Tags:

This may be a silly question, but it tackled me.

I've started learning rust, from the allmighty book. In the iterator chapter (the one linked therein) there's the following example

fn iterator_demonstration() {
    let v1 = vec![1, 2, 3];

    let mut v1_iter = v1.iter();

    assert_eq!(v1_iter.next(), Some(&1));
    assert_eq!(v1_iter.next(), Some(&2));
    assert_eq!(v1_iter.next(), Some(&3));
    assert_eq!(v1_iter.next(), None);
}

The book kinda glazed over it, but I wonder - why are the ampersands needed?

edit: just to clarify - I do understand iter iterates through immutable references. I just don't quite grasp referencing a numeric literal (again, rookie question.)

like image 976
avshyz Avatar asked Dec 27 '17 23:12

avshyz


People also ask

What does iterator next () returns?

2. next(): Returns the next element in the iteration. It throws NoSuchElementException if no more element is present.

What does iterator next () return in Java?

Returns true if the iteration has more elements. Returns the next element in the iteration. Removes from the underlying collection the last element returned by this iterator (optional operation).

Is there a next method in iterator?

Iterator interface provides the following methods: boolean hasNext() - Returns true if the iteration has more elements. E next() - Returns the next element in the iteration. void remove() - Removes from the underlying collection the last element returned by the iterator (optional operation).

Does iterator next return the first element?

next() returns the next element in the sequence, starting with the first element.


1 Answers

Because they're pointers. Follow the docs.

  • v1 is a Vec<i32>. So T is i32.
  • Vec doesn't have an iter method. It does Deref to [T]. Scroll down further.
  • [T] has an iter method. It returns a std::slice::Iter<T>.
  • v1_iter is an Iter<i32>, so T is i32.
  • next is part of the Iterator trait, so scroll down and look for the impl Iterator section.
  • Just below, it specifies that next returns an Option<&'a T>. Substitute T, and that gives you Option<&'a i32>.

Pre-emptive: Why are they pointers?

Because that's what you asked for. If you wanted to move the contents of the Vec out via an iterator, you need to use Vec::into_iter or Vec::drain.

like image 166
DK. Avatar answered Sep 23 '22 13:09

DK.