for - Rust
Description: API documentation for the Rust `for` keyword in crate `std`.
Keywords: rust, rustlang, rust-lang, for

# [−]Keyword for

The `for` keyword.

`for` is primarily used in for-in-loops, but it has a few other pieces of syntactic uses such as `impl Trait for Type` (see `impl` for more info on that). for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over an exceedingly common practice within Rust, which is to loop over an iterator until that iterator returns None (or `break` is called).

    for i in 0..5 {
        println!("{}", i * 2);
    }

    for i in std::iter::repeat(5) {
        println!("turns out {} never stops being 5", i);
        break; // would loop forever otherwise
    }

    'outer: for x in 5..50 {
        for y in 0..10 {
            if x == y {
                break 'outer;
            }
        }
    }Run

As shown in the example above, `for` loops (along with all other loops) can be tagged, using similar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving the same tag to `break` breaks the tagged loop, which is useful for inner loops. It is definitely not a goto.

A `for` loop expands as shown:

    for loop_variable in iterator {
        code()
    }Run

    {
        let mut _iter = std::iter::IntoIterator::into_iter(iterator);
        loop {
            match _iter.next() {
                Some(loop_variable) => {
                    code()
                },
                None => break,
            }
        }
    }Run

More details on the functionality shown can be seen at the `IntoIterator` docs.

For more information on for-loops, see the Rust book or the Reference.

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g., `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g., `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g., `str,u8` or `String,struct:Vec,test`)