如何在结构中有未使用的类型参数? [英] How can I have an unused type parameter in a struct?

查看:29
本文介绍了如何在结构中有未使用的类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新我编写的一些旧代码,基本上如下所示:

I'm trying to update some older code I wrote that basically looks like:

trait Foo<T>{}

struct Bar<A, B: Foo<A>>{
  b: B
}

这曾经完全正常,但现在我收到编译错误:

This used to work totally fine, but now I am getting a compile error:

src/test.rs:19:12: 19:13 error: parameter `A` is never used
src/test.rs:19 struct Bar<A, B: Foo<A>> {
                          ^
src/test.rs:19:12: 19:13 help: consider removing `A` or using a marker such as `core::marker::PhantomData`

所以我可以尝试删除类型参数并得到如下内容:

So I can try to remove the type parameter and get something like this:

struct Bar<A>{
  b: Foo<A>
}

然而这并不是我真正想要的.在我的原始代码中 B 解析为一个大小的类型,但现在 Foo 是未大小的.

however this is not really what I want. In my original code B resolves to a sized type, but now Foo<A> is unsized.

另一个建议的解决方案是尝试使用错误提到的这个 PhantomData,结果是:

The other suggested solution is to try using this PhantomData the error mentions, resulting in:

struct Bar<A, B: Foo<A>> {
  b: B,
  marker: PhantomData<A>
}

但这对我来说似乎很混乱.阅读 PhantomData 的文档似乎表明这意味着要与不安全的代码一起使用,但我在这里的任何地方都没有使用不安全的代码.我想要的只是让 Bar 包含一个实现 Foo 的类型的实例.

but this seems really messy to me. Reading the docs for PhantomData seem to indicate this is meant to be used with unsafe code, but I am not working with unsafe code anywhere here. All I want is for Bar to contain an instance some type that implements Foo.

这真的是现在处理这种情况的唯一方法,还是我遗漏了什么?

Is this really the only way to handle this situation now, or am I missing something?

推荐答案

根据你真正的 Foo 是怎样的,你也许可以使用关联类型来代替,就像这样:

Depending on how your real Foo is, you might be able to work with associated types instead, like this:

trait Foo{ type T; }

struct Bar<B: Foo> {
  b: B,
}

否则(如果您确实需要 Foo 上的类型参数),PhantomData 确实是要走的路.

otherwise (if you do need to have the type parameter on Foo), PhantomData is indeed the way to go.

您不是唯一一个发现 PhantomData 的文档令人困惑的人(参见 PhantomData 难以理解).因此,PhantomData 已经最近由 Steve Klabnik 改进,现在确实如此明确提及这种情况(而不仅仅是不安全的代码).

You were not the only person finding PhantomData's docs confusing (see PhantomData is incomprehensible). As a result, the documentation for PhantomData has been recently improved by Steve Klabnik and now it does mention this scenario explicitly (and not just unsafe code).

这篇关于如何在结构中有未使用的类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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