依赖于Rust中另一个泛型的泛型类型 [英] Generic types that depend on another generic in Rust

查看:62
本文介绍了依赖于Rust中另一个泛型的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通用的结构,以该通用实现特质为界.特质本身就是通用的.这是Rust 1.49.0.

I'm trying to create a struct that is generic, with a bound that the generic implement a trait. The trait is itself generic. This is in Rust 1.49.0.

如果我这样做:

trait Foo<T> {}

struct Baz<F: Foo<T>> {
    x: F,
}

我收到编译错误,因为未定义 T .但是,如果我定义它:

I get a compilation error, because T is not defined. But if I define it:

trait Foo<T> {}

struct Baz<T, F: Foo<T>> {
    x: F,
}

然后我得到一个编译器错误,因为 T 未被使用.

then I get a compiler error because T is unused.

唯一的选择似乎是包括一个 PhantomData< T> 字段,但是如果我的一般依赖性变得更加复杂,这将变得更加笨拙:

The only option seems to be to include a PhantomData<T> field, but if my generic dependence becomes more complicated, this starts to get more unwieldy:

use std::marker::PhantomData;

trait Foo<T> {}

struct Baz<T, U, F: Foo<T>, G: Foo<U>> {
    phantom_t: PhantomData<T>,
    phantom_u: PhantomData<U>,
    x: F,
    y: G,
}

我的一半领域都是幻影!该结构几乎被困扰.

Half of my fields are phantoms! The struct is practically haunted.

我的问题是:最后编译的例子真的是惯用的Rust吗?如果是这样,为什么Rust不能 not 不能检测到实际使用了 Baz< Foo< T>> 中的 T ?

My question is: Is the example at the end that compiles really idiomatic Rust? And if so, why can Rust not detect that the T in Baz<T, Foo<T>> is actually used?

推荐答案

最后的例子是编译成真的Rust吗?

Is the example at the end that compiles really idiomatic Rust?

存储多个幻像类型参数的惯用方式是使用元组:

The idiomatic way to store multiple phantom type parameters is with tuples:

struct Baz<T, U, F: Foo<T>, G: Foo<U>> {
    x: F,
    y: G,
    _t: PhantomData<(T, U)>,
}

为什么Rust无法检测到 Baz< Foo< T>> 中的 T 实际被使用?

由于 variance <,这实际上是预期的行为删除检查.这里的想法是,编译器需要知道它可以对类型参数 T 施加哪些约束,并且使用 PhantomData 类型将指导编译器如何做到这一点.

This is actually intended behavior due to variance and the drop check. The idea here is that the compiler needs to know what constraints it can put on the type parameter T, and usage of the PhantomData type will instruct the compiler how it can do so.

您可以在 Rust nomicon .

这篇关于依赖于Rust中另一个泛型的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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