简体   繁体   English

如何约束相互依赖的特征的通用类型 arguments?

[英]How can I constrain generic type arguments of a trait which depend on each other?

I have a trait for types which process data:对于处理数据的类型,我有一个特征:

pub trait Stage<I, O>: Sized {}

Here, I and O represent the input and output data types respectively.这里, IO分别代表输入和 output 数据类型。 I want to create an implementation of Stage which combines two other Stage s:我想创建一个结合了其他两个StageStage实现:

pub struct CompoundStage<S0: Stage<_, _>, S1: Stage<_, _>>(S0, S1);

CompoundStage must itself be a Stage : CompoundStage本身必须是Stage

impl<S0: Stage<_, _>, S1: Stage<_, _>> Stage<S0::I, S1::O> for CompoundStage<S0, S1> {}

How can I constrain the type arguments of CompoundStage such that the “intermediate” type is consistent (ie S0::O == S1::I )?如何约束CompoundStage的类型 arguments 以使“中间”类型一致(即S0::O == S1::I )? I know I could do it by adding another type parameter like below, but is there a cleaner way?我知道我可以通过添加另一个类型参数来做到这一点,如下所示,但有没有更清洁的方法?

pub struct CompoundStage<S0: Stage<_, T>, S1: Stage<T, _>, T>(S0, S1);

impl<S0: Stage<_, T>, S1: Stage<T, _>, T> Stage<S0::I, S1::O> for CompoundStage<S0, S1, T> {}

You probably want a trait with associated types instead of generic types:可能想要一个具有关联类型而不是泛型类型的特征:

pub trait Stage: Sized {
    type I;
    type O;
}

pub struct CompoundStage<S0, S1>(S0, S1);

impl<S0, S1> Stage for CompoundStage<S0, S1>
where
    S0: Stage,
    S1: Stage<I = S0::O>,
{
    type I = S0::I;
    type O = S1::O;
}

See also:也可以看看:


If you must use generic types, you will need to introduce PhantomData :如果必须使用泛型类型,则需要引入PhantomData

use std::marker::PhantomData;

pub trait Stage<I, O>: Sized {}

pub struct CompoundStage<S0, S1, M>(S0, S1, PhantomData<M>);

impl<S0, S1, I, O, M> Stage<I, O> for CompoundStage<S0, S1, M>
where
    S0: Stage<I, M>,
    S1: Stage<M, O>,
{
}

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

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