next method
- Rust course
- Intermediate
- Lesson 49/115
- 4 min
Drain elements one by one with next.
The next method
next can be called by hand too. The iterator variable must be mut, because each call advances it; an exhausted iterator keeps returning None:
let v = vec!["a", "b"];
let mut it = v.iter();
println!("{:?}", it.next()); // Some("a")
println!("{:?}", it.next()); // Some("b")
println!("{:?}", it.next()); // NoneA for loop does exactly this behind the scenes: it calls next until None.
Consuming methods
Some methods consume the iterator by calling next to the end and produce a result: sum, count, collect, last, max. A consumed iterator can't be used again (it has been moved):
let it = vec![1, 2, 3].into_iter();
let toplam: i32 = it.sum();
// it.count(); // error: it was moved into sum
println!("{toplam}"); // 6nth(n) and find advance the iterator only as far as needed.
Practice Advancing by hand
For let v = vec!["a", "b"];, create let mut it = v.iter(); and call next() three times, printing the results with {:?} on one line.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let v = vec!["a", "b"];
let mut it = v.iter();
let a = it.next();
let b = it.next();
let c = it.next();
println!("{:?} {:?} {:?}", a, b, c);
}Expected output
Some("a") Some("b") None
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What do <code>iter()</code>, <code>iter_mut()</code> and <code>into_iter()</code> produce, in order?
- &T, &T, &T
- T, &mut T, &T
- &T, &mut T, T Correct answer
- T, T, T
Explanation: into_iter consumes the collection and gives ownership of the elements.
2 Advance
let mut it = v.iter();
let ilk = it.____();
let mut it = v.iter();
let ilk = it.next();
Explanation: next advances the iterator one step and gives the element inside an Option.
3 Method and result on [1, 2, 3]
| Term | Meaning |
|---|---|
.iter().count() |
3 |
.iter().last() |
Some(3) |
.iter().nth(1) |
Some(2) |
.iter().nth(5) |
None |