Function lending_iterator::from_fn
source · pub fn from_fn<Item, State, Next>(
state: State,
next: Next
) -> FromFn<Item, State, Next> ⓘwhere
Item: HKT,
Next: FnMut(&mut State) -> Option<Feed<'_, Item>>,
Expand description
Main ad-hoc / closure-based constructor of LendingIterator
s.
It expects the both necessary and sufficient elements for such an impl:
-
a
State
, which will play a role akin to that ofSelf
in a manual impl; -
a
fn next
“method” on it. There is actually a certain level of flexibility gained from this being a closure rather than a stateless associated function.For instance, non-lent state (such as an internal mutable counter) can be implicity captured by such a closure, without having to funnel it through the lendable
State
.
Example
-
use ::lending_iterator::prelude::*; struct Person { name: String, age: u8, } fn example (person: &mut Person) -> impl '_ + LendingIterator /* or: -> impl '_ + LendingIteratorDyn<Item = HKT!(&str)> */ { lending_iterator::from_fn::<HKT!(&str), _, _>( person, |p| if p.age > 0 { Some(&p.name) } else { None }, ) }
Remarks
It can also be viewed as a convenience layer over:
::lending_iterator::repeat_mut(state)
.filter_map::<Item, _>(move |[], it| next(it))
-
use ::lending_iterator::prelude::*; struct Person { name: String, age: u8, } fn example (person: &mut Person) -> impl '_ + LendingIterator /* or: -> impl '_ + LendingIteratorDyn<Item = HKT!(&str)> */ { lending_iterator::repeat_mut(person) .filter_map::<HKT!(&str), _>( |[], p| if p.age > 0 { Some(&p.name) } else { None }, ) }
FromFn
The returned struct
—FromFn
— can also be used directly, to benefit
from “named arguments”, at the cost of having to provide a PhantomData
parameter.