Rust loops: Difference between revisions

From wikinotes
(Created page with "= loop = <blockquote> <syntaxhighlight lang="rust"> loop { // loop forever } </syntaxhighlight> </blockquote><!-- loop -->")
 
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
= loop =
= General =
<blockquote>
== Breaking/Continuing etc. ==
<blockquote>
<syntaxhighlight lang="rust">
break;    // exit loop
continue;  // skip to next iteration of loop
</syntaxhighlight>
 
Break can be assigned a return value
<syntaxhighlight lang="rust">
break 123  // return value '123' from loop
</syntaxhighlight>
</blockquote><!-- Breaking/Continuing etc. -->
 
== Loop Labels ==
<blockquote>
Loops can be assigned labels, so that you can target which loop to break out of.
<syntaxhighlight lang="rust">
'outer_loop: loop {
    loop {
        break 'outer_loop;
    }
}
</syntaxhighlight>
</blockquote><!-- Loop Labels -->
</blockquote><!-- General -->
 
 
= loops =
<blockquote>
<blockquote>
<syntaxhighlight lang="rust">
<syntaxhighlight lang="rust">
Line 7: Line 36:
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- loop -->
</blockquote><!-- loop -->
= while loops =
<blockquote>
<syntaxhighlight lang="rust">
let mut num = 0;
while num < 5 {
    index += 1;
}
</syntaxhighlight>
</blockquote><!-- while -->
= for loops =
<blockquote>
<syntaxhighlight lang="rust">
let cats = ["boulie", "icarus", "lucifer"];
for cat in cats {
    println!("{cat}");
}
</syntaxhighlight>
</blockquote><!-- for loops -->

Latest revision as of 14:50, 7 February 2023

General

Breaking/Continuing etc.

break;     // exit loop
continue;  // skip to next iteration of loop

Break can be assigned a return value

break 123  // return value '123' from loop

Loop Labels

Loops can be assigned labels, so that you can target which loop to break out of.

'outer_loop: loop {
    loop {
        break 'outer_loop;
    }
}


loops

loop {
    // loop forever
}

while loops

let mut num = 0;

while num < 5 {
    index += 1;
}

for loops

let cats = ["boulie", "icarus", "lucifer"];

for cat in cats {
    println!("{cat}");
}