“parameter `'a` is never used” error when 'a is used in type parameter bound

后端 未结 3 2166
use std::iter::Iterator;

trait ListTerm<\'a> {
    type Iter: Iterator;
    fn iter(&\'a self) -> Self::Iter;
}

enum TermVa         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 14:42

    'a clearly is being used.

    Not as far as the compiler is concerned. All it cares about is that all of your generic parameters are used somewhere in the body of the struct or enum. Constraints do not count.

    What you might want is to use a higher-ranked lifetime bound:

    enum TermValue
    where
        for<'a> LT: 'a + ListTerm<'a> + Sized,
    {
        Str(LT),
    }
    

    In other situations, you might want to use PhantomData to indicate that you want a type to act as though it uses the parameter:

    use std::marker::PhantomData;
    
    struct Thing<'a> {
        // Causes the type to function *as though* it has a `&'a ()` field,
        // despite not *actually* having one.
        _marker: PhantomData<&'a ()>,
    }
    

    And just to be clear: you can use PhantomData in an enum; put it in one of the variants:

    enum TermValue<'a, LT>
    where
        LT: 'a + ListTerm<'a> + Sized,
    {
        Str(LT, PhantomData<&'a ()>),
    }
    

提交回复
热议问题