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

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

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

enum TermVa         


        
3条回答
  •  借酒劲吻你
    2020-11-30 14:48

    If you aren't using an associated type (like >::Iter) in the enum definition, you probably don't need to make 'a a parameter at all.

    I assume you want the LT: ListTerm<'a> bound so that you can write one or more fns or an impl that uses LT as a ListTerm. In which case, you can easily parameterize the type with just , and put the 'a generic and trait bound only on the items that require it:

    trait ListTerm<'a> {
        type Iter: Iterator;
        fn iter(&'a self) -> Self::Iter;
    }
    
    enum TermValue {  // no 'a parameter here...
        Str(LT),
    }
    
    impl<'a, LT> TermValue  // ... just here
    where
        LT: ListTerm<'a>,
    {
        fn iter(&'a self) -> LT::Iter {
            match *self {
                TermValue::Str(ref term) => term.iter(),
            }
        }
    }
    

    Some standard library types like std::collections::HashMap do this: the K: Hash + Eq bound isn't on the type itself. Alternatively, you could have a where clause on each method where the bound is needed. The difference between a where clause on an impl and one on a fn is not significant unless you're implementing a trait (see this question).

    The main reason for using PhantomData is that you want to express some constraint that the compiler can't figure out by itself. You don't need PhantomData to express "Any TermData is only valid as long as its contained LT is valid", because the compiler already enforces that (by "peering inside" the type, as in Matthieu's answer).

提交回复
热议问题