Box to generic Trait with missing type parameter

#1
  1. Suppose we have:
pub trait Foo {
  type A;
  type B;
  ...
}
  1. Now, I can get Boxes of objects satisfying the trait by saying
    Box< Foo<A = i32, B = f32 > >

  2. However, suppose I want to say: Box to some Foo, where A = i32, but we don’t care what B is. Is that possible? I.e. something like:

Box < Foo<A = i32, B = no_idea> >
#2

No, because in general the trait Foo could depend on type B in a way that is incompatible with type erasure.

trait Foo {
    type A;
    type B;
    
    fn get(&self, b: &Self::B) -> Self::A;
}

In this case, you cannot ignore B, because it is an important part of Foo. Since this is possible, and in fact common, it wouldn’t be possible to ignore B.

What you could do is something like this,

fn take_foo<B>(b: Box<dyn Foo<A = i32, B = B>>) {
    ...
}

This way, it doesn’t matter what B is, you could still use it in this function.

2 Likes
#3

Well, I suppose you could hide such methods, similar to methods with a Self: Sized bound.

But, I think a common approach here is to use two traits (when they’re under one’s control):

trait FooA {
   type A;
}

trait FooB: FooA {
    type B;
}

Then use FooA where you don’t care about B.

5 Likes