diff options
Diffstat (limited to 'Returning values from loops.md')
-rw-r--r-- | Returning values from loops.md | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/Returning values from loops.md b/Returning values from loops.md new file mode 100644 index 0000000..7f0b116 --- /dev/null +++ b/Returning values from loops.md @@ -0,0 +1,23 @@ +[[Rust]] +[[A scope block is an expression]] +[[Loop labels]] + + +A loop can return values, it is an expression. Thus it can be used in an assignment as well. +It is possible to `return ` but that would exit the function, instead we can also `break expression;` and return a value just from the loop by breaking it with a value (as we would normally write a `return`). + +```rust +fn main() { + let mut counter = 0; + + let result = loop { + counter += 1; + + if counter == 10 { + break counter * 2; + } + }; + + println!("The result is {result}"); +} +``` |