gpt4 book ai didi

generics - 依赖于 Rust 中另一个泛型的泛型类型

转载 作者:行者123 更新时间:2023-12-03 11:32:26 28 4
gpt4 key购买 nike

我正在尝试创建一个通用的结构,具有通用实现特征的界限。特征本身是通用的。这是在 Rust 1.49.0 中。

如果我这样做:

trait Foo<T> {}

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

我得到一个编译错误,因为 T没有定义。但是如果我定义它:

trait Foo<T> {}

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

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

唯一的选择似乎是包含一个 PhantomData<T>领域,但如果我的通用依赖变得更加复杂,这将开始变得更加笨拙:

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

我一半的领域是幻影!该结构实际​​上闹鬼了。

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

最佳答案

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

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

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

why can Rust not detect that the T in Baz<T, Foo<T>> is actually used?

这实际上是由于 variance 而导致的预期行为和 drop check .这里的想法是,编译器需要知道它可以对类型参数 T 施加哪些约束。 ,以及 PhantomData 的用法type 将指示编译器如何执行此操作。

您可以了解更多关于 PhantomData 的信息以及它如何影响 Rust nomicon 中的方差.

关于generics - 依赖于 Rust 中另一个泛型的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65960825/

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