I\'m trying to create a struct with a field, generic over F
where F
implements something like: Fn(&mut Compiler, &[Token]) -> &Tok
As per @Stargateur's comment, the solution was to add a Higher-Ranked Trait Bound to the Fn
trait declaration. The where for
clause is a piece of syntax completely specific to this use case.
Normal lifetime bounds don't work, because we don't know what lifetimes will be applied to the function's arguments until call time.
So we go from this:
struct Rule<F> where F: Fn(&mut Compiler, &[Token]) -> &Token {
func: F
}
To this:
struct Rule<F> where for<'a> F: Fn(&mut Compiler, &'a[Token]) -> &'a Token {
func: F
}
Which dictates that the trait bounds applied to function F
must satisfy all potential lifetimes of 'a
at call time. Magic!