Take While And Skip While Stop At First Miss
take_while keeps the matching prefix and skip_while drops it — both stop at the first failing item, unlike filter which scans everything.
Code
fn main() {
// 已排序的温度序列:take_while 取前缀,skip_while 跳过前缀
let temps = [-8i16, -3, 0, 4, 11, 19, 27];
let freezing: Vec<i16> = temps.iter().copied().take_while(|&t| t < 0).collect();
println!("freezing: {freezing:?}");
let above_zero: Vec<i16> = temps.iter().copied().skip_while(|&t| t < 0).collect();
println!("above zero: {above_zero:?}");
// 与 filter 不同:两者在首个不满足项处短路,不再扫完整条序列
let below_11: Vec<i16> = temps.iter().copied().take_while(|&t| t < 11).collect();
println!("stop at first miss: {below_11:?}");
// 组合:跳过冰点前缀后取接下来两项
let after_thaw: Vec<i16> = temps
.iter()
.copied()
.skip_while(|&t| t < 0)
.take(2)
.collect();
println!("first two above zero: {after_thaw:?}");
}How the snippet works
main is the whole program: four collect() calls over the temps slice demonstrate take_while, skip_while, the short-circuit at t < 11, and a combined skip_while(...).take(2) chain.
Applying it
Each adaptor prints its collected Vec<i16> under its own label — freezing:, above zero:, stop at first miss: — so the kept prefix and the skipped prefix sit side by side for comparison.
Statements that matter
let above_zero: Vec<i16> = temps.iter().copied().skip_while(|&t| t < 0).collect();
let below_11: Vec<i16> = temps.iter().copied().take_while(|&t| t < 11).collect();
let freezing: Vec<i16> = temps.iter().copied().take_while(|&t| t < 0).collect();
Interactive Tools for This Topic
FAQ
- What does Take While And Skip While Stop At First Miss print when run?
- Execute the whole file; each printed line is prefixed with a label like `freezing:`, `above zero:`, `stop at first miss:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.