Require a trait to implement a Distribution<T> for the Standard Distribution

Viewed 221

I am trying to build a trait that requires implementors to implment the Distribution for the Standard distribution of the rand crate.

I have recently learn how to make this a trait implementor to also implement the display trait with SuperTraits and I would like to do a similar thing for the trait bound Standard: Distribution<Self>. I can add this trait bound with a where clause as such:

use rand::{Rng, distributions::{Distribution, Standard}}; // rand 0.7
use std::fmt;

trait SampleAndDisplay: fmt::Display + Sized
where
    Standard: Distribution<Self>
{
    fn other_requirement() -> u16;
}

// For any type to implement SampleAndDisplay, they need the following at least:
struct Implementor;

impl SampleAndDisplay for Implementor {
    fn other_requirement() -> u16 {
        // ...
    }
}

impl fmt::Display for Implementor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // ...
    }
}

impl Distribution<Implementor> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Implementor {
        // ...
    }
}

But the problem I have with this is I now need to add an additional trait bound whenever I use SampleAndDisplay:

fn func<T>()
where
    T: SampleAndDisplay,
    Standard: Distribution<T>, // Would like to not have to always put this
{
    // ...
}

In a sense, I think I would like to do the following, but I can't figure out the right syntax, or this is even possible:

trait SampleAndDisplay: (Standard: Distribution<Self>) + fmt::Display + Sized
{
    fn other_requirement() -> u16;
}

Any help is appreciated.

0 Answers
Related