How to express this complex struct definition which uses closures and multiple layers of higher-ranked lifetimes in Rust?
⚓ Rust 📅 2026-04-10 👤 surdeus 👁️ 5If it is even possible, how would I write the following in Rust:
A
Parseris (wrapper around) a function which takes some&'txt strand returns anIter, which is an iterator returning pairs of which the first halve is a slice of the input text, and the second halve is some type,Out, which also borrows from'txt.
In pseudocode, this would look like:
struct Parser<Func, Iter, Out>(Func)
where
Func : for <'txt> Fn(&'txt str) -> Iter<'txt>,
Iter<'txt> : Iterator<Item = (&'txt str, Out<'txt>)>;
This is as far as I've come:
/// Generic lifetime GAT trait
trait Lt { type Of<'lt>; }
/// Used to restrict the Item of an Iterator to be (&'a, X<'a>)
trait IterItem_Trait<'a>
{
type L : Lt;
fn get(self) -> (&'a str, <Self::L as Lt>::Of<'a>);
}
/// Used to track the overarching type of the `Of<>` GAT
#[repr(transparent)]
struct IterItem_Type<'txt, L : Lt>((&'txt str, L::Of<'txt>));
impl<'a, L : Lt> IterItem_Trait<'a> for IterItem_Type<'a, L> {
type L = L;
#[inline(always)]
fn get(self) -> (&'a str, <Self::L as Lt>::Of<'a>) {
self.0
}
}
struct Parser<Func, Iter>(Func)
where
Iter : for <'any> Iterator<Item : IterItem_Trait<'any>>,
Func : for <'txt> Fn(&'txt str) -> Iter;
However, this does not bind Iter's 'any to Func's 'txt and so this does not compile:
fn test() {
// Raw<T> implements Lt with `Of<> = T`
let take1 = Parser(move |input| {
let mut input = input.chars();
let c = input.next().unwrap();
let rest = input.as_str();
std::iter::once( IterItem_Type::<Raw<char>>((rest, c)) )
});
}
3 posts - 3 participants
🏷️ Rust_feed