core/iter/sources/from_fn.rs
1use crate::fmt;
2
3/// Creates an iterator with the provided closure
4/// `F: FnMut() -> Option<T>` as its [`next`](Iterator::next) method.
5///
6/// The iterator will yield the `T`s returned from the closure.
7///
8/// This allows creating a custom iterator with any behavior
9/// without using the more verbose syntax of creating a dedicated type
10/// and implementing the [`Iterator`] trait for it.
11///
12/// Note that the `FromFn` iterator doesn’t make assumptions about the behavior of the closure,
13/// and therefore conservatively does not implement [`FusedIterator`],
14/// or override [`Iterator::size_hint()`] from its default `(0, None)`.
15///
16/// The closure can use captures and its environment to track state across iterations. Depending on
17/// how the iterator is used, this may require specifying the [`move`] keyword on the closure.
18///
19/// [`move`]: ../../std/keyword.move.html
20/// [`FusedIterator`]: crate::iter::FusedIterator
21///
22/// # Examples
23///
24/// Let’s re-implement the counter iterator from [module-level documentation]:
25///
26/// [module-level documentation]: crate::iter
27///
28/// ```
29/// let mut count = 0;
30/// let counter = std::iter::from_fn(move || {
31/// // Increment our count. This is why we started at zero.
32/// count += 1;
33///
34/// // Check to see if we've finished counting or not.
35/// if count < 6 {
36/// Some(count)
37/// } else {
38/// None
39/// }
40/// });
41/// assert_eq!(counter.collect::<Vec<_>>(), &[1, 2, 3, 4, 5]);
42/// ```
43#[inline]
44#[stable(feature = "iter_from_fn", since = "1.34.0")]
45pub fn from_fn<T, F>(f: F) -> FromFn<F>
46where
47 F: FnMut() -> Option<T>,
48{
49 FromFn(f)
50}
51
52/// An iterator where each iteration calls the provided closure `F: FnMut() -> Option<T>`.
53///
54/// This `struct` is created by the [`iter::from_fn()`] function.
55/// See its documentation for more.
56///
57/// [`iter::from_fn()`]: from_fn
58#[derive(Clone)]
59#[stable(feature = "iter_from_fn", since = "1.34.0")]
60pub struct FromFn<F>(F);
61
62#[stable(feature = "iter_from_fn", since = "1.34.0")]
63impl<T, F> Iterator for FromFn<F>
64where
65 F: FnMut() -> Option<T>,
66{
67 type Item = T;
68
69 #[inline]
70 fn next(&mut self) -> Option<Self::Item> {
71 (self.0)()
72 }
73}
74
75#[stable(feature = "iter_from_fn", since = "1.34.0")]
76impl<F> fmt::Debug for FromFn<F> {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 f.debug_struct("FromFn").finish()
79 }
80}