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.)
2. next(): Returns the next element in the iteration. It throws NoSuchElementException if no more element is present.
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).
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).
next() returns the next element in the sequence, starting with the first element.
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.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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With