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