::lending-iterator
Fully generic LendingIterator
s in stable Rust.
-
this pattern used to be called
StreamingIterator
, but sinceStream
s entered the picture (as theasync/.await
version ofIterator
s, that is,AsyncIterator
s), it has been deemed more suitable to go for the lending naming convention.- (this could be even more relevant since you can have a
LendingIterator
lendingimpl Future
s, which would effectively make it another flavor ofAsyncIterator
, but not quite theStream
variant).
- (this could be even more relevant since you can have a
-
For context, this crate is a generalization of other crates such as:
which hard-code their lending
Item
type to&_
andResult<&_, _>
respectively.This crate does not hardcode such dependent types, and thus encompasses both of those traits, and infinitely more!
-
Mainly, it allows lending
&mut _
Item
s, which means it can handle the infamously challengingwindows_mut()
pattern!
Examples
windows_mut()
!
use *;
let mut array = ;
array = 1;
// Cumulative sums are trivial with a `mut` sliding window,
// so let's showcase that by generating a Fibonacci sequence.
let mut iter = array.;
while let Some = iter.next
assert_eq!;
Rolling your own version of it using the handy from_fn
constructor
- (Or even the
FromFn
flavor of it to enjoy "named arguments")
use *;
let mut array = ;
array = 1;
// Let's hand-roll our iterator lending `&mut` sliding windows:
let mut iter = ;
while let Some = iter.next
assert_eq!;
-
where that HKT!(&mut [u16; 3]) is a higher-kinded type parameter that has to be turbofished to let the generic context properly figure out the return type of the
next
closure.Indeed, if we were to let type inference, alone, figure it out, it wouldn't be able to know which lifetimes would be fixed/tied to call-site captures, and which would be tied to the "lending-ness" of the iterator (higher-order return type). See
::higher-order-closure
for more info about this.
LendingIterator
adapters
See lending_iterator::adapters
.
Bonus: Higher-Kinded Types (HKT)
See higher_kinded_types
for a presentation about them.
Real-life usage: .sort_by_key()
that is fully generic over the key lending mode
As noted in this 6-year-old issue:
Such an API can easily be provided using the HKT API of this crate:
use ;
// ---- Demo ----