loop¶
Level: 101 → 201 · for newcomers
One line: loop repeats forever and is left with break — and because break can carry a value, loop is the one loop in Rust that is routinely used as an expression: let x = loop { … break v; };.
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The bullets below are the questions the finished page has to answer.
What it has to cover¶
loop { }with no condition, and why a dedicated keyword beatswhile true: the compiler knows aloopwithoutbreaknever finishes, so it type-checks the code after it differentlybreak value— the reason this page is separate fromwhile.whileandforalways evaluate to(); onlyloopcan produce a value- The idiom it exists for: retry-until-success, and a read loop that ends on a sentinel
- Its type is
!(never) when nothing breaks, which is whylet x: i32 = loop {};compiles - Where it turns into
while letor an iterator, and why that is usually the better ending
The trap it exists for¶
while true and loop are not interchangeable to the compiler even though they run the same: flow analysis treats loop as definitely-not-returning and while true as a condition that might one day be false, so the two differ on whether a following let is considered initialised. Clippy's while_immutable_condition and the never_loop lint both live in this neighbourhood.
See also¶
breakandcontinue— the keyword this loop depends on, and labels for the nested casewhileloops — the condition-at-the-top version- A block is an expression — the rule that lets a loop have a value at all
- Comprehensive Rust:
loop↗
Po polsku¶
loop kręci się w nieskończoność i wychodzi się z niego przez break — i tylko w tej jednej pętli break potrafi nieść wartość, dzięki czemu let x = loop { … break v; }; w ogóle ma sens; while i for zawsze dają (). Polskie kursy programowania uczą zwykle pętli nieskończonej jako while (true), ale w Ruscie to nie jest ta sama konstrukcja i nie chodzi tu o styl: analiza przepływu traktuje loop jako pętlę, która na pewno się nie kończy (jej typem jest wtedy !, never, i dlatego let x: i32 = loop {}; się kompiluje), a while true jako warunek, który kiedyś może okazać się fałszywy. Widać to w praktyce: obie wersje inaczej odpowiadają na pytanie, czy let postawiony za pętlą uchodzi za zainicjowany; w tej samej okolicy mieszkają linty clippy o nazwach while_immutable_condition i never_loop. Typowe zastosowania to „próbuj, aż się uda” i czytanie do napotkania wartownika; jeśli da się to zapisać jako while let albo jako iterator, zwykle właśnie tak warto skończyć.
Szukaj po polsku: pętla nieskończona · break z wartością · typ ! never · rust loop vs while true · rust break value from loop