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?
enumerateis perfectly appropriate when you need the index. There's no reason to avoid it.enumerate.