Skip to content

Commit f7a6638

Browse files
committed
Document for keyword
1 parent a5c4a38 commit f7a6638

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

src/libstd/keyword_docs.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,77 @@ mod extern_keyword { }
292292
/// [Reference]: https://doc.rust-lang.org/reference/items/functions.html
293293
mod fn_keyword { }
294294

295+
#[doc(keyword = "for")]
296+
//
297+
/// The `for` keyword.
298+
///
299+
/// `for` is primarily used in for-in-loops, but it has a few other pieces of syntactic uses such as
300+
/// `impl Trait for Type` (see [`impl`] for more info on that). for-in-loops, or to be more
301+
/// precise, iterator loops, are a simple syntactic sugar over an exceedingly common practice
302+
/// within Rust, which is to loop over an iterator until that iterator returns None (or [`break`]
303+
/// is called).
304+
///
305+
/// ```rust
306+
/// for i in 0..5 {
307+
/// println!("{}", i * 2);
308+
/// }
309+
///
310+
/// for i in std::iter::repeat(5) {
311+
/// println!("turns out {} never stops being 5", i);
312+
/// break; // would loop forever otherwise
313+
/// }
314+
///
315+
/// 'outer: for x in 5..50 {
316+
/// for y in 0..10 {
317+
/// if x == y {
318+
/// break 'outer;
319+
/// }
320+
/// }
321+
/// }
322+
/// ```
323+
///
324+
/// As shown in the example above, `for` loops (along with all other loops) can be tagged, using
325+
/// similar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving the
326+
/// same tag to `break` breaks the tagged loop, which is useful for inner loops. It is definitely
327+
/// not a goto.
328+
///
329+
/// A `for` loop expands as shown:
330+
///
331+
/// ```rust
332+
/// # fn code() { }
333+
/// # let iterator = 0..2;
334+
/// for loop_variable in iterator {
335+
/// code()
336+
/// }
337+
/// ```
338+
///
339+
/// ```rust
340+
/// # fn code() { }
341+
/// # let iterator = 0..2;
342+
/// {
343+
/// let mut _iter = std::iter::IntoIterator::into_iter(iterator);
344+
/// loop {
345+
/// match _iter.next() {
346+
/// Some(loop_variable) => {
347+
/// code()
348+
/// },
349+
/// None => break,
350+
/// }
351+
/// }
352+
/// }
353+
/// ```
354+
///
355+
/// More details on the functionality shown can be seen at the [`IntoIterator`] docs.
356+
///
357+
/// For more information on for-loops, see the [Rust book] or the [Reference].
358+
///
359+
/// [`impl`]: keyword.impl.html
360+
/// [`break`]: keyword.break.html
361+
/// [`IntoIterator`]: iter/trait.IntoIterator.html
362+
/// [Rust book]: https://doc.rust-lang.org/book/2018-edition/ch03-05-control-flow.html#looping-through-a-collection-with-for
363+
/// [Reference]: https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops
364+
mod for_keyword { }
365+
295366
#[doc(keyword = "let")]
296367
//
297368
/// The `let` keyword.

0 commit comments

Comments
 (0)