Bar<x> = Rc<Foo<X, Y>> -- for some Y, we don't care what Y is

I have the following:

struct Foo<X, Y> ...

Now, I want to define a new type Bar<X> where Bar<x> = Rc<Foo<X, Y>> -- for some Y -- we don't care what Y is.

Questions:

  1. is there a formal name for this type of Type ?

  2. is there a way to do this in Rust ?

  3. if not, what is the recommended way to change the problem so it is solvable in Rust ?

You need to introduce a trait to erase the Y type like that.

pub struct Foo<X, Y> {
    x: X,
    y: Y,
}

pub trait FooTrait {
    type FooX;
    fn get_x(&self) -> &Self::FooX;
}

impl<X, Y> FooTrait for Foo<X, Y> {
    type FooX = X;
    fn get_x(&self) -> &X {
        &self.x
    }
}

You can then define

type Bar<X> = Rc<dyn FooTrait<FooX = X>>;

playground

1 Like

Pedantic question: Why does FooTrait use an associated type instead of pub trait FooTrait<X> ?

Is it solely because Foo<X, Y> uniquely determines the FooX of FooTrait ?

Both associated types and generic parameters would work. I used an associative type because of the uniqueness as you mentioned.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.