# [−][src]Function std::iter::unfold

ⓘImportant traits for Unfold<St, F>

### Important traits for Unfold<St, F>

`impl<St, T, F> Iterator for Unfold<St, F> where
F: FnMut(&mut St) -> Option<T>, type Item = T;`

    pub fn unfold<St, T, F>(initial_state: St, f: F) -> Unfold<St, F> where
        F: FnMut(&mut St) -> Option<T>,

🔬 This is a nightly-only experimental API. (`iter_unfold` #55977)

Creates a new iterator where each iteration calls the provided closure `F: FnMut(&mut St) -> Option<T>`.

This allows creating a custom iterator with any behavior without using the more verbose syntax of creating a dedicated type and implementing the `Iterator` trait for it.

In addition to its captures and environment, the closure is given a mutable reference to some state that is preserved across iterations. That state starts as the given `initial_state` value.

Note that the `Unfold` iterator doesn’t make assumptions about the behavior of the closure, and therefore conservatively does not implement `FusedIterator`, or override `Iterator::size_hint` from its default `(0, None)`.

# Examples

Let’s re-implement the counter iterator from module-level documentation:

    #![feature(iter_unfold)]
    let counter = std::iter::unfold(0, |count| {
        // Increment our count. This is why we started at zero.
        *count += 1;

        // Check to see if we've finished counting or not.
        if *count < 6 {
            Some(*count)
        } else {
            None
        }
    });
    assert_eq!(counter.collect::<Vec<_>>(), &[1, 2, 3, 4, 5]);Run

# 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`)