Vec of `rand::distributions::Distribution` trait objects?

Is there any way to create a vector of rand::distributions::Distribution trait objects, i.e. Vec<Box<dyn Distribution<f64>>>? When I try to do so, the compiler fails with mesage "the trait cannot be made into an object because method sample has generic type parameters".

1 Like

Not directly, because sample is generic on the Rng type, and there would need to be a sample method per Rng implementer.

If you're okay fixing the type of Rng as well, you can work around it with your own trait.

2 Likes

Your example can be modified to implement Distribution<T> for trait objects of the extension trait:

pub trait DynDistribution<T> {
    fn sample_(&self, rng: &mut dyn RngCore) -> T;
}

impl<D, T> DynDistribution<T> for D
where
    D: Distribution<T>,
{
    fn sample_(&self, rng: &mut dyn RngCore) -> T {
        <Self as Distribution<T>>::sample(self, rng)
    }
}

impl<T> Distribution<T> for dyn DynDistribution<T>+'_ {
    fn sample<R:Rng+?Sized>(&self, mut rng: &mut R)->T {
        self.sample_(&mut rng)
    }
}

Playground

1 Like