<p>The Rust programming language has an infinite loop construct, which looks like this:</p>
<pre class="lang-rust prettyprint-override"><code>loop {
   &lt;some code&gt;
}
</code></pre>
<p>It's the only language I can think of that has dedicated syntax for this; in most other languages some variation of <code>while true</code> is used instead. Why does Rust have it?</p>

<syntax><language-comparison><control-flow><loops><rust>
Why does Rust have an infinite loop construct?
CC BY-SA 4.0
2023-05-19T17:23:29.770Z
Although it isn't necessarily good practice, note that this can also be replicated in C (and some other languages), such as with `#define forever while (1)` and then you can just do `forever { ... }`
cocomac
CC BY-SA 4.0
2023-05-19T17:25:58.717Z
Ruby has this too
naffetS
CC BY-SA 4.0
2023-05-19T22:25:02.740Z
QBasic has something similar with `DO ... LOOP`, although you can also add a `WHILE` or `UNTIL` condition to either the `DO` or the `LOOP`.
DLosc
CC BY-SA 4.0
2023-05-21T14:19:38.390Z
Ada has loop ... end loop, in part because of exit (C/Rust break)/return statements and in part because of a need to loop infinitely in some low-level programs.
prosfilaes
CC BY-SA 4.0
2023-11-26T02:33:18.453Z
Turing also has `loop ... end loop`
joelw
<p>While <code>loop</code> may have been added with returning values in mind, making this just a bonus, infinitely looping until a <code>break</code> is encountered is pretty common across languages (with constructs like <code>while (1)</code> or <code>for (;;)</code> likely being familiar to most), and giving this dedicated syntax saves keystrokes and improves readability.</p>
<p>E.g., Ruby has this <code>loop</code> syntax (along with a similarly sugary <code>until</code>), yet doesn't have the value-returning feature, showing that the readability advantage is itself worth considering in a vacuum.</p>

CC BY-SA 4.0
2023-06-27T14:04:01.837Z
2023-06-27T14:04:01.837Z
rydwolf
CC BY-SA 4.0
2023-06-27T19:41:44.457Z
[It was not added with returning values in mind, though.](/q/698/799#comment2296_702)
user3840170
<p><code>loop</code> was <a href="https://github.com/rust-lang/rust/issues/1906" rel="noreferrer">originally added</a> to Rust to allow for functions whose body was an infinite loop to not need a <code>return</code> statement after the loop. Other languages get around this by treating loops as definitely infinite only when the controlling expression is the literal <code>true</code> (e.g. <a href="https://godbolt.org/z/hEshfcYnG" rel="noreferrer">Dart</a>, <a href="https://godbolt.org/z/zK7738j5f" rel="noreferrer">TypeScript</a>) or a compile-time constant that evaluates to true (e.g. <a href="https://docs.oracle.com/javase/specs/jls/se20/html/jls-14.html#jls-14.22-300-Q" rel="noreferrer">JLS§14.22</a>, <a href="https://godbolt.org/z/8qM9qqWhd" rel="noreferrer">Zig</a>, <a href="https://godbolt.org/z/KK7TW9Y9j" rel="noreferrer">D</a>).</p>

CC BY-SA 4.0
2023-06-28T11:56:01.490Z
2023-06-28T11:56:01.490Z
HMPerson1
<p>The rust <code>loop {}</code> syntax has a unique feature: it has a return value. Consider this code:</p>
<pre class="lang-rs prettyprint-override"><code>let val = loop {
   let random_number = rng::random();
   if random_number &lt; 0.5 {
       break random_number;
   }
}
</code></pre>
<p>This will set val to the first random number below 0.5. This wouldn't work for any other kind of loop since they could potentially exit before hitting a <code>break</code>.</p>
<p>Other languages don't have this because they have statements distinct from expressions, so loops don't return anything. In rust all other loops return <code>()</code></p>
<p>This feature was actually added later, initially the <code>loop{}</code> construct existed as the only way to create a <code>!</code> &quot;never&quot; type.</p>

CC BY-SA 4.0
2023-05-19T17:22:39.527Z
2023-06-28T13:45:04.987Z
2023-06-28T13:45:04.987Z
mousetail 'he-him'
CC BY-SA 4.0
2023-05-19T17:32:47.557Z
Great answer! I actually used it for exactly this just yesterday, to implement Parsec's `many :: Parser a -> Parser [a]` in Rust. Loop until you get an `Err` then break and check the error.
Silvio Mayolo
CC BY-SA 4.0
2023-05-20T03:15:39.680Z
Worth adding that `while` loops cannot have the same feature, because they might terminate without breaking. A language *could* have `while` loops which produce optional values, but this would be inconvenient for the use-case where the only loop exit is a `break` which does produce a value.
kaya3
CC BY-SA 4.0
2023-05-20T06:04:05.483Z
`while` and `for` loops could have the same feature if they also have an `else` clause, which only executes when the loop does not exit via `break`. Python is the most well known language that supports an `else` clause after loops, but the only language I'm aware of that also supports `while ... else` and `for ... else` returning values is Zig.
Olive
CC BY-SA 4.0
2023-06-27T14:05:50.667Z
One way this could possibly be implemented for `while` loops is using the value of the last expression in the block if it terminates due to the condition (like other constructs do). E.g., `let mut x = 10; while x > 4 { x -= 1; x * 2 }` would return `8`
rydwolf
CC BY-SA 4.0
2023-06-27T14:07:02.993Z
@RydwolfPrograms What if the loop runs 0 times?
mousetail 'he-him'
CC BY-SA 4.0
2023-06-27T14:08:52.607Z
@mousetail Oh, fair...I suppose you could have it wrap the output in an `Option` and do `None` if it never runs...this would probably work more optimally with a `do while`, but that's basically just a `loop` anyway
rydwolf
CC BY-SA 4.0
2023-06-27T15:43:32.240Z
This explanation is anachronistic. Return values were only [added to `loop` in 2016](https://github.com/rust-lang/rfcs/pull/1624), so they cannot be possibly the reason the `loop` construct exists in the first place.
user3840170
CC BY-SA 4.0
2023-06-27T15:48:02.307Z
It's the main purpose now though
mousetail 'he-him'
# Why does Rust have an infinite loop construct?
Posted by: username_0 on 2023-05-19
The Rust programming language has an infinite loop construct, which looks like this:
loop {
   
}

It's the only language I can think of that has dedicated syntax for this; in most other languages some variation of while true is used instead. Why does Rust have it?
**Tags:** syntax language-comparison control-flow loops rust
> **Comments:**
> **username_1**: Although it isn't necessarily good practice, note that this can also be replicated in C (and some other languages), such as with `#define forever while (1)` and then you can just do `forever { ... }`  
> **username_2**: Ruby has this too  
> **username_3**: QBasic has something similar with `DO ... LOOP`, although you can also add a `WHILE` or `UNTIL` condition to either the `DO` or the `LOOP`.  
> **username_4**: Ada has loop ... end loop, in part because of exit (C/Rust break)/return statements and in part because of a need to loop infinitely in some low-level programs.  
> **username_5**: Turing also has `loop ... end loop`  
---
## 3 answers
### Answer by username_9 on 2023-05-19. Score: 23 | Accepted answer
The rust loop {} syntax has a unique feature: it has a return value. Consider this code:
let val = loop {
   let random_number = rng::random();
   if random_number < 0.5 {
       break random_number;
   }
}

This will set val to the first random number below 0.5. This wouldn't work for any other kind of loop since they could potentially exit before hitting a break.
Other languages don't have this because they have statements distinct from expressions, so loops don't return anything. In rust all other loops return ()
This feature was actually added later, initially the loop{} construct existed as the only way to create a ! "never" type.
> **Comments:**
> **username_10** (2023-05-19): Great answer! I actually used it for exactly this just yesterday, to implement Parsec's `many :: Parser a -> Parser [a]` in Rust. Loop until you get an `Err` then break and check the error.  
> **username_11** (2023-05-20): Worth adding that `while` loops cannot have the same feature, because they might terminate without breaking. A language *could* have `while` loops which produce optional values, but this would be inconvenient for the use-case where the only loop exit is a `break` which does produce a value.  
> **username_12** (2023-05-20): `while` and `for` loops could have the same feature if they also have an `else` clause, which only executes when the loop does not exit via `break`. Python is the most well known language that supports an `else` clause after loops, but the only language I'm aware of that also supports `while ... else` and `for ... else` returning values is Zig.  
> **username_6** (2023-06-27): One way this could possibly be implemented for `while` loops is using the value of the last expression in the block if it terminates due to the condition (like other constructs do). E.g., `let mut x = 10; while x > 4 { x -= 1; x * 2 }` would return `8`  
> **username_9** (2023-06-27): @RydwolfPrograms What if the loop runs 0 times?  
> **username_6** (2023-06-27): @mousetail Oh, fair...I suppose you could have it wrap the output in an `Option` and do `None` if it never runs...this would probably work more optimally with a `do while`, but that's basically just a `loop` anyway  
> **username_7** (2023-06-27): This explanation is anachronistic. Return values were only [added to `loop` in 2016](https://github.com/rust-lang/rfcs/pull/1624), so they cannot be possibly the reason the `loop` construct exists in the first place.  
> **username_9** (2023-06-27): It's the main purpose now though  
---
### Answer by username_8 on 2023-06-28. Score: 8
`loop` was [originally added](https://github.com/rust-lang/rust/issues/1906) to Rust to allow for functions whose body was an infinite loop to not need a `return` statement after the loop. Other languages get around this by treating loops as definitely infinite only when the controlling expression is the literal `true` (e.g. [Dart](https://godbolt.org/z/hEshfcYnG), [TypeScript](https://godbolt.org/z/zK7738j5f)) or a compile-time constant that evaluates to true (e.g. [JLS§14.22](https://docs.oracle.com/javase/specs/jls/se20/html/jls-14.html#jls-14.22-300-Q), [Zig](https://godbolt.org/z/8qM9qqWhd), [D](https://godbolt.org/z/KK7TW9Y9j)).
---
### Answer by username_6 on 2023-06-27. Score: 4
While `loop` may have been added with returning values in mind, making this just a bonus, infinitely looping until a `break` is encountered is pretty common across languages (with constructs like `while (1)` or `for (;;)` likely being familiar to most), and giving this dedicated syntax saves keystrokes and improves readability.

E.g., Ruby has this `loop` syntax (along with a similarly sugary `until`), yet doesn't have the value-returning feature, showing that the readability advantage is itself worth considering in a vacuum.
> **Comments:**
> **username_7** (2023-06-27): [It was not added with returning values in mind, though.](/q/698/799#comment2296_702)  
---
