Greetings,
I've seen a number of posts on StackOverflow (and perhaps here) dedicated to the trait cannot be made into an object...
error for traits using generics.
Simple example:
use num::{Complex, Zero, One};
trait HasNumber {
fn favorite<T: Zero + One> (&self) > T;
}
struct Has1 {}
impl HasNumber for Has1 {
fn favorite<T: Zero + One> (&self) > T { T::zero() }
}
struct Has2 {}
impl HasNumber for Has2 {
fn favorite<T: Zero + One> (&self) > T { T::one() }
}
fn main(){
let h1 = Has1{};
h1.favorite::<f64>();
h1.favorite::<Complex<f64>>();
let h2 = Has2{};
h2.favorite::<f64>();
h2.favorite::<Complex<f64>>();
let v: Vec<Box <dyn HasNumber>> = vec![ // <= problem's here
Box::new(Has1{}),
Box::new(Has2{}),
];
}
Errors:

4  trait HasNumber {
  this trait cannot be made into an object...
5  fn favorite<T: Zero + One> (&self) > T;
Playground:
https://play.rustlang.org/?version=stable&mode=debug&edition=2018&gist=292710263badd277e827b849f49fb3c0
My question: what is the idiomatic Rust version of this combination (generics + "dynamic" dispatch)?
Of course in my nonsimplifiedreality there are far more than two things like Has1
and Has2
. And they have aways more elaborate behavior (hence the desired for Box<dyn>
).
Thanks!