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

前端 未结 2 1513
花落未央
花落未央 2020-12-12 02:41
pub trait AllValues {
    fn all_values() -> Vec where Self: std::marker::Sized;
}

use rand::Rand;
use rand::Rng;
impl Ra         


        
相关标签:
2条回答
  • 2020-12-12 03:21

    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:

    • How do I implement a trait I don't own for a type I don't own?
    0 讨论(0)
  • 2020-12-12 03:30

    I see now where my mistake in interpretation was. Quoting from the the traits section of the book:

    There’s one more restriction on implementing traits: either the trait or the type you’re implementing it for must be defined by you. Or more precisely, one of them must be defined in the same crate as the impl you're writing.

    (Emphasis added.)

    Since I was trying to implement a trait I must have read that as "either the trait or the trait you’re implementing it for". This discussion about an eventually implemented rfc specifically mentions a similar case to the one I presented : impl<T: Copy> Clone for T as something that would not be allowed.

    Creating a wrapper type as suggested elsewhere is one solution for this problem. Assuming the ownership of the type implementations allows it, implementing the trait explicitly for each concrete instance, (optionally condensing the code with a macro,) as suggested here is another.

    0 讨论(0)
提交回复
热议问题