What type would you want to return? The associated type presumably? If so, I'm not aware of any good pleasing way to accomplish this. Here's something I hacked up using Any
but it's not something I would build a system on top of :
use std::any::Any;
trait MyTrait {
type Assoc: Any;
fn get(&self) -> &Self::Assoc;
}
struct Foo;
impl MyTrait for Foo {
type Assoc = i32;
fn get(&self) -> &i32 {
&5
}
}
struct Bar;
impl MyTrait for Bar {
type Assoc = &'static str;
fn get(&self) -> &Self::Assoc {
&"hello"
}
}
trait Erased {
fn get(&self) -> &Any;
}
impl<M, A: 'static> Erased for M
where
M: MyTrait<Assoc = A>,
{
fn get(&self) -> &Any {
self.get() as &Any
}
}
fn main() {
let v: Vec<Box<Erased>> = vec![Box::new(Foo), Box::new(Bar)];
let x: &i32 = v[0].get().downcast_ref().unwrap();
println!("{}", x);
let y: &&str = v[1].get().downcast_ref().unwrap();
println!("{}", y);
}
If you can unify all the associated types to some common trait that they impl, you can remove the Any
bit in favor of a normal trait object. Alternatively, perhaps you can redesign things so that you don't need to expose the associated type like this at all.
Have you considered using an enum instead of trait objects?
Anyway, if you elaborate some more on your scenario there might be better suggestions.