How to define lifetimes on a Fn trait bound returning references?

前端 未结 1 336
心在旅途
心在旅途 2021-01-26 21:47

I\'m trying to create a struct with a field, generic over F where F implements something like: Fn(&mut Compiler, &[Token]) -> &Tok

相关标签:
1条回答
  • 2021-01-26 22:14

    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!

    0 讨论(0)
提交回复
热议问题