简体   繁体   中英

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.

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:

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

But because Node is generic, I need to introduce another type parameter, looking something like this:

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? 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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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