Self::It-6ren">
gpt4 book ai didi

rust - "parameter ` 'a` 从未使用 "error when ' a 用于类型参数绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 11:47:23 25 4
gpt4 key购买 nike

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.



就编译器而言,并非如此。它所关心的只是你所有的泛型参数都在 struct 的主体中的某处使用。或 enum .约束不计算在内。

您可能想要的是使用排名更高的生命周期界限:
enum TermValue<LT>
where
for<'a> LT: 'a + ListTerm<'a> + Sized,
{
Str(LT),
}

在其他情况下,您可能需要使用 PhantomData表示您希望一个类型表现得好像它使用参数一样:
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 ()>,
}

为了清楚起见:您可以使用 PhantomDataenum ;将其放入其中一种变体中:
enum TermValue<'a, LT>
where
LT: 'a + ListTerm<'a> + Sized,
{
Str(LT, PhantomData<&'a ()>),
}

关于rust - "parameter ` 'a` 从未使用 "error when ' a 用于类型参数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64847153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com