Specialize trait implementation based on where conditions

Hello together,

I want to change the behavior for the trait implementation of a struct based on some input types, which I am trying to constrain using the where syntax.
Here is a toy example. I define a trait that takes an u32 input and outputs something:

trait Transform {
    type Out;
    fn transform(&self, i: u32) -> Self::Out;
}

Now the tuple transform takes an existing implementation of transform and adds the u32 by building a tuple:

struct TupleTransform<Base>
where Base: Transform{
    base: Base
}

impl<Base> Transform for TupleTransform<Base>
where Base: Transform {
    type Out = (Base::Out, u32);
    fn transform(&self, i: u32) -> (Base::Out, u32) {
        (self.base.transform(i), i)
    }
}

Now I want to "specialize" this trait implementation for the case, that the base transormer outputs a tuple. In that case I want to extend the tuple:

impl<Base, A, B> Transform for TupleTransform<Base>
    where Base: Transform<Out=(A,B)>{
    type Out = (A,B, u32);
    fn transform(&self, i: u32) -> (Base::Out, u32) {
        (self.base.transform(i).0, self.base.tranform(i).1, i)
    }
}

Rust does not allow me this specialization.

Now I could solve this by adding another struct "Tuple2Transform" and implement the specialized trait for that.

But is it somehow possible to archive this specialization with only one type?

Thanks!
Nathan

You don't need quotes. What you are trying to do is, quite literally, called specialization.

It's even used in Rust's standard library, but, unfortunately, it's not sound (as in: it can be used to create UB in safe Rust). There are smaller, less powerful version which you can use on nightly, but that one, too, have some problems thus it's not even on Rust 2024 roadmap.

I guess if you want to use nightly features you can pick it, otherwise you'll need some other design for your program.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.