while let
循环
与 if let
一样,with let
变体会针对一个模式重复测试一个值:
fn main() { let v = vec![10, 20, 30]; let mut iter = v.into_iter(); while let Some(x) = iter.next() { println!("x: {x}"); } }
Here the iterator returned by v.into_iter()
will return a Option<i32>
on every call to next()
. It returns Some(x)
until it is done, after which it will return None
. The while let
lets us keep iterating through all items.
如需详细了解 Rust 中 的模式,请参阅模式匹配。
- 指出只要值与模式匹配,
while let
循环就会一直进行下去。 - 你可以使用 if 语句将
while let
循环重写为无限循环,当iter.next()
没有值可以解封时中断。while let
为上述情况提供了语法糖。