Skip to content

Commit d56466f

Browse files
authored
Rollup merge of #65544 - dorfsmay:doc_keyword_break, r=Dylan-DPC
Added doc on keyword break RE: #34601
2 parents 1ba7b4e + 11214a6 commit d56466f

File tree

1 file changed

+65
-2
lines changed

1 file changed

+65
-2
lines changed

src/libstd/keyword_docs.rs

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,72 @@ mod as_keyword { }
3333
//
3434
/// Exit early from a loop.
3535
///
36-
/// The documentation for this keyword is [not yet complete]. Pull requests welcome!
36+
/// When `break` is encountered, execution of the associated loop body is
37+
/// immediately terminated.
38+
///
39+
/// ```rust
40+
/// let mut last = 0;
41+
///
42+
/// for x in 1..100 {
43+
/// if x > 12 {
44+
/// break;
45+
/// }
46+
/// last = x;
47+
/// }
48+
///
49+
/// assert_eq!(last, 12);
50+
/// println!("{}", last);
51+
/// ```
52+
///
53+
/// A break expression is normally associated with the innermost loop enclosing the
54+
/// `break` but a label can be used to specify which enclosing loop is affected.
55+
///
56+
///```rust
57+
/// 'outer: for i in 1..=5 {
58+
/// println!("outer iteration (i): {}", i);
59+
///
60+
/// 'inner: for j in 1..=200 {
61+
/// println!(" inner iteration (j): {}", j);
62+
/// if j >= 3 {
63+
/// // breaks from inner loop, let's outer loop continue.
64+
/// break;
65+
/// }
66+
/// if i >= 2 {
67+
/// // breaks from outer loop, and directly to "Bye".
68+
/// break 'outer;
69+
/// }
70+
/// }
71+
/// }
72+
/// println!("Bye.");
73+
///```
74+
///
75+
/// When associated with `loop`, a break expression may be used to return a value from that loop.
76+
/// This is only valid with `loop` and not with any other type of loop.
77+
/// If no value is specified, `break;` returns `()`.
78+
/// Every `break` within a loop must return the same type.
79+
///
80+
/// ```rust
81+
/// let (mut a, mut b) = (1, 1);
82+
/// let result = loop {
83+
/// if b > 10 {
84+
/// break b;
85+
/// }
86+
/// let c = a + b;
87+
/// a = b;
88+
/// b = c;
89+
/// };
90+
/// // first number in Fibonacci sequence over 10:
91+
/// assert_eq!(result, 13);
92+
/// println!("{}", result);
93+
/// ```
94+
///
95+
/// For more details consult the [Reference on "break expression"] and the [Reference on "break and
96+
/// loop values"].
97+
///
98+
/// [Reference on "break expression"]: ../reference/expressions/loop-expr.html#break-expressions
99+
/// [Reference on "break and loop values"]:
100+
/// ../reference/expressions/loop-expr.html#break-and-loop-values
37101
///
38-
/// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
39102
mod break_keyword { }
40103

41104
#[doc(keyword = "const")]

0 commit comments

Comments
 (0)