22

I'm trying to find a way of checking if I am on the last element of an iterator in a for loop without using .clone(); currently I'm doing this:

let sentence = "The quick brown fox.";
let words = sentence.split(' ');
let last = words.clone().last().unwrap();
 
for word in words {
    if word == last {
        print!("{}", word);
    }
} 

I've also tried using .collect() on the iterator, but this requires that I use .iter().enumerate() to check for the last index, which seems unnecessarily complicated to me:

let sentence = "The quick brown fox.";
let words: Vec<&str> = sentence.split(' ').collect();
 
for (i, word) in words.iter().enumerate() {
    if i == words.len() - 1 {
        print!("{}", word);
    }
}

Is there a way to do this in a more succinct way, perhaps just using the original iterator?

3
  • 2
    BTW using enumerate is perfectly appropriate when you need the index. There's no reason to avoid it. Commented Jun 7, 2021 at 13:21
  • @DenysSéguret It just seemed redundant to me that I have to convert the iterator to a vector, then I convert it back to an iterator again to get the index Commented Jun 7, 2021 at 14:16
  • This conversion to vec is a legit concern yes. In the general case of the last iterator's item, you can find below Masklinn's answer which elegantly buffer the next element. In your exact case you have mine which is simpler and more efficient. But in the very general case of really needing the index, use enumerate. Commented Jun 7, 2021 at 14:17

5 Answers 5

42

Convert your iterator to a Peekable.

This will require desugaring the iteration to a while let, but if during the iteration peek() returns None you're on the last iteration:

let mut it = sentence.split(' ').peekable();
while let Some(word) = it.next()  {
    if it.peek().is_none() {
        println!("{}", word);
    }
}

Playground.

1
  • I was initially wondering why this wasn't working for me until I realized you have to turn the for-loop into a while-loop. Skim reading is not always perfect, haha.
    – Noah May
    Commented Sep 20 at 18:17
8

For the general case of finite iterators, if you want to get the last item, you can, as suggests @Masklinn (see their answer), convert to a Peekable which will buffer so it always knows the next element.

In your precise case, when you just want to print the last word and don't care about the other ones, there is a much cheaper solution because splitting on a character implements DoubleEndedIterator.

So it's easy to get the last word, you don't have to collect the whole split nor to enumerate. It's also fast as the string will be searched from the end and nothing will be copied.

So you can do

let last_word = sentence
    .split(' ').rev().next().unwrap(); // SAFETY: there's always at least one word
1
  • 3
    There is a totally general solution via peekable (though of course the results may be unexpected if fed an infinite iterator).
    – Masklinn
    Commented Jun 7, 2021 at 13:47
8

This may not be as performant as the other answers, but this is cleaner - you can use itertools's with_position():

use itertools::Itertools;

let sentence = "The quick brown fox.";
let words = sentence.split(' ');

for (pos, word) in words.with_position() {
    if let itertools::Position::Last | itertools::Position::Only = pos {
        print!("{}", word);
    }
}

You can also check for other conditions, such as first, middle etc..

4
  • This is the best answer. It also lets you check if the item is the first element. It uses Peekable under the hood so I don't think it will really be any slower than any of the other answers.
    – Timmmm
    Commented Aug 17, 2023 at 10:20
  • The only slightly annoying this is you need to check for Only too, and there's no is_first or is_last which checks for both for you.
    – Timmmm
    Commented Aug 17, 2023 at 10:22
  • @Timmmm have you tried contributing it? Looking at the repo bluss did seem inclined a few years back so that might be a shoe-in for a contrib.
    – Masklinn
    Commented Oct 23 at 8:44
  • I didn't think about it tbh. It would be good though - feel free!
    – Timmmm
    Commented Oct 24 at 14:16
4

You could take advantage of the Iterator::map() iterator adaptor for achieving a more convenient usage:

let sentence = "The quick brown fox.";
let words: Vec<&str> = sentence.split(' ').collect();

for (word, is_last_element) in words.iter().enumerate()
  .map(|(i, w)| (w, i == words.len() - 1))
{
   if is_last_element {
      println!("{}", word);
   }
}

This way, instead of having to deal with the index in the body of the loop, you just focus on whether or not the given element in a particular iteration is the last one.

0
3

I would like to add to @Masklinn 's answer.

I have used a trait to make it a little more readable.

The code allows it.peek().is_none() to be written as it.is_last().

trait IterEndPeek {
    fn is_last(&mut self) -> bool;
}

impl<I: Iterator> IterEndPeek for  std::iter::Peekable<I> {
    fn is_last(&mut self) -> bool {
        self.peek().is_none()
    }
}

fn main() {
    let sentence = "The quick brown fox.";
    let mut it = sentence.split(' ').peekable();
    while let Some(word) = it.next()  {
        if it.is_last() {
            println!("last {}", word);
        } else {
            println!("- {}", word);
        }
    }
}
3
  • 1
    It is so useful that I made a tiny crate just for it ! crates.io/crates/iter_peek_end
    – Thomas
    Commented Oct 29 at 15:21
  • A have not looked at this is a while. I am wondering why the mut is needed. Commented Nov 16 at 16:04
  • Hello, the mutable reference in is_last() is required because the method peek() on a Peekable iterator require a mutable reference : doc.rust-lang.org/std/iter/… Even too you just want to "read" the next value of the peekable iterator, the peekable iterator may need to move forward (internally) in order to do the look ahead of the next value, if the next value was not already "peeked"/generated, even if the peekable iterator will not move :)
    – Thomas
    Commented Nov 16 at 17:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.