macro_rules! for_each {
($pattern:pat in $($rem:tt)*) => { ... };
}
Expand description
Iterates over all elements of an iterator,
const equivalent of Iterator::for_each
§Iterator methods
This macro supports emulating iterator methods by expanding to equivalent code.
The supported iterator methods are documented in the iterator_dsl
module,
because they are also supported by other konst::iter
macros.
§Examples
§Custom iterator
use konst::iter::{IntoIterKind, IsIteratorKind};
struct Upto10(u8);
impl IntoIterKind for Upto10 { type Kind = IsIteratorKind; }
impl Upto10 {
const fn next(mut self) -> Option<(u8, Self)> {
if self.0 < 10 {
let ret = self.0;
self.0 += 1;
Some((ret, self))
} else {
None
}
}
}
const N: u32 = {
let mut n = 0u32;
konst::iter::for_each!{elem in Upto10(7) =>
n = n * 10 + elem as u32;
}
n
};
assert_eq!(N, 789);
§Summing pairs
This example requires the "rust_1_51"
feature, because it uses const generics.
use konst::iter::for_each;
const fn add_pairs<const N: usize>(l: [u32; N], r: [u32; N]) -> [u32; N] {
let mut out = [0u32; N];
for_each!{(i, val) in &l,zip(&r),map(|(l, r)| *l + *r),enumerate() =>
out[i] = val;
}
out
}
assert_eq!(add_pairs([], []), []);
assert_eq!(add_pairs([3], [5]), [8]);
assert_eq!(add_pairs([3, 5], [8, 13]), [11, 18]);