简体   繁体   English

Rust 限制泛型参数的泛型参数

[英]Rust limit generic parameter of generic parameter

I've defined a trait Node<T: Ord + Eq + std::fmt::Debug> to provide standard operations for a tree's node - I was originally using an enum, but I'm thinking that this approach will be a bit more flexible and cut down on some verbosity.我已经定义了一个特征Node<T: Ord + Eq + std::fmt::Debug>来为树的节点提供标准操作 - 我最初使用的是枚举,但我认为这种方法会有点更灵活,减少一些冗长。

I want to declare an 'internal node' structure which contains a set of the same types, each implementing node for the same type.我想声明一个“内部节点”结构,其中包含一组相同的类型,每个实现节点的类型相同。 If Node was not generic, I'd declare that like this:如果 Node 不是通用的,我会这样声明:

struct InternalNode<T: Node>(Vec<T>);

But because Node is generic, I need to introduce another type parameter, looking something like this:但是因为 Node 是泛型的,所以我需要引入另一个类型参数,看起来像这样:

struct InternalNode<E: Ord + Eq + std::fmt::Debug, T: Node<E>>(
    Vec<T>,
);

With that solution, the compiler complains that E is unused, despite my use of it in the declaration of type parameter T. I assume I'm just guessing the syntax for this behavior incorrectly, could anyone help me out?使用该解决方案,编译器抱怨 E 未使用,尽管我在类型参数 T 的声明中使用了它。我假设我只是错误地猜测了这种行为的语法,有人能帮我吗? Thanks!谢谢!

Generic parameters defined on a struct have to be used, you can mark it as used by adding a PhantomData field, a zero sized generic type for such cases.必须使用在结构上定义的泛型参数,您可以通过添加PhantomData字段将其标记为已使用,这种情况下的泛型类型为零。

use std::marker::PhantomData;

pub trait Node<T> { }

struct InternalNode<E: Ord + Eq + std::fmt::Debug, T: Node<E>>(
    Vec<T>, 
    PhantomData::<E>,
);

You can then construct it as such:然后你可以这样构造它:

InternalNode(vec![someNode, someOtherNode], PhantomData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM