Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

rust - "parameter `'a` is never used" error when 'a is used in type parameter bound

use std::iter::Iterator;

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

enum TermValue<'a, LT>
where
    LT: ListTerm<'a> + Sized + 'a,
{
    Str(LT),
}
error[E0392]: parameter `'a` is never used
 --> src/main.rs:8:16
  |
8 | enum TermValue<'a, LT>
  |                ^^ unused type parameter
  |
  = help: consider removing `'a` or using a marker such as `std::marker::PhantomData`

'a clearly is being used. Is this a bug, or are parametric enums just not really finished? rustc --explain E0392 recommends the use of PhantomData<&'a _>, but I don't think there's any opportunity to do that in my use case.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

'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<LT>
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 ()>),
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...