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:
-
is there a formal name for this type of Type ?
-
is there a way to do this in Rust ?
-
if not, what is the recommended way to change the problem so it is solvable in Rust ?
alice
2
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
?
alice
4
Both associated types and generic parameters would work. I used an associative type because of the uniqueness as you mentioned.
1 Like
system
Closed
5
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.