我试图找到一种方法来检查我是否在 for 循环中的迭代器的最后一个元素上而不使用 .clone(); 目前我正在这样做:
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);
}
}
我也试过在迭代器上使用 .collect() ,但这要求我使用 .iter().enumerate() 来检查最后一个索引,这对我来说似乎不必要地复杂:
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);
}
}
有没有办法以更简洁的方式做到这一点,也许只是使用原始迭代器?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句