07.循环结构for、while、loop
<h1>07.循环结构for、while、loop</h1>
<h2>1、for</h2>
<pre><code>let collection = [1, 2, 3, 4, 5];
for i in 0..collection.len() {
let item = collection[i];
// ...
}
//循环中获取元素的索引
fn main() {
let a = [4, 3, 2, 1];
// `.iter()` 方法把 `a` 数组变成一个迭代器
for (i, v) in a.iter().enumerate() {
println!(&quot;第{}个元素是{}&quot;, i + 1, v);
}
}</code></pre>
<h2>2、while</h2>
<pre><code>fn main() {
let mut n = 0;
while n &lt;= 5 {
println!(&quot;{}!&quot;, n);
n = n + 1;
}
println!(&quot;我出来了!&quot;);
}</code></pre>
<h2>3、loop无条件循环</h2>
<p>需要自己使用break跳出循环</p>
<pre><code>fn main() {
loop {
println!(&quot;again!&quot;);
}
}</code></pre>
<h2>4、break跳出整个循环,循环结束</h2>
<pre><code> for i in 1..4 {
if i == 2 {
break;
}
println!(&quot;{}&quot;, i);
}</code></pre>
<h2>5、continue</h2>
<p>继续下一次循环</p>
<pre><code> for i in 1..4 {
if i == 2 {
continue;
}
println!(&quot;{}&quot;, i);
}</code></pre>