“从不使用参数‘a’"在类型参数绑定中使用 'a 时出错 [英] "parameter `'a` is never used" error when 'a is used in type parameter bound

查看:26
本文介绍了“从不使用参数‘a’"在类型参数绑定中使用 'a 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 显然正在被使用.这是一个错误,还是参数枚举还没有真正完成?rustc --explain E0392 推荐使用 PhantomData<&'a _>,但我认为在我的用例中没有任何机会这样做.

'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.

推荐答案

'a 显然正在被使用.

就编译器而言并非如此.它所关心的只是您的所有通用参数都在structenum 的主体中的某处使用.约束不算数.

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),
}

在其他情况下,您可能希望使用 PhantomData 来指示您希望类型的行为好像它使用参数:

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

要明确一点:你可以enum中使用PhantomData;把它放在其中一种变体中:

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

这篇关于“从不使用参数‘a’"在类型参数绑定中使用 'a 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆