From 00a52e3d631df0a7610f4f17a9bd6d60205239fd Mon Sep 17 00:00:00 2001 From: Jasper Ras Date: Mon, 4 Aug 2025 08:46:49 +0200 Subject: vault backup: 2025-08-04 08:46:49 --- Returning values from loops.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Returning values from loops.md (limited to 'Returning values from loops.md') 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}"); +} +``` -- cgit v1.2.3