Can’t implement a trait I don’t own for all types that implement a trait I do own

I should be able to implement Rand for AllValues since AllValues is defined in my crate.

No, you are only allowed to implement your own trait AllValues for types you didn’t define. You can’t make the logical jump to implementing an unrelated trait that you also didn’t define.

There are two considerations to remember:

  • If your trait is public (which it is based on the code you’ve provided), you aren’t the only one that can implement the trait. Consumers of your crate might be able to implement it for their own types, where they might also decide to implement Rand!
  • The rand crate might decide to implement Rand for T some time in the future.

What is the right way to implement Rand for things that implement AllValues?

I don’t believe there is one. I’d just introduce a wrapper type that holds a value or a reference to a value that implements your trait and implement Rand for that.

See also:

Leave a Comment