Test
Test

Reputation: 1720

Automatically impl From<&T> after defining From<T>

Consider the following MRE:

struct A {}
struct B {}

impl From<A> for B {
    fn from(t: A) -> B { B {} }
}

Is it possible to automatically implement From<&A> for B?

Upvotes: 4

Views: 695

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170723

The direction you want is not possible. E.g. consider a struct Str which doesn't implement Clone, and A=B=Str. Then there is impl From<A> for B (that is, impl From<Str> for <Str>), but how could you write

fn from(t: &Str) -> Str

which you need for impl From<&A> for B?

It makes some sense going the other way: if you have an impl From<&A> for B, then you can easily define impl From<A> for B:

impl From<A> for B {
    fn from(t: A) -> B { From::from(&t) }
}

There is still no built-in way to do it (as kmdreko's reply says), but it's possible.

It also makes sense if you add a requirement that A: Clone.

Upvotes: 0

kmdreko
kmdreko

Reputation: 59952

No. You will have to write it yourself.

impl From<&A> for B {
    fn from(a: &A) -> B {
        unimplemented!("implement me")
    }
}

The only blanket implementation for From is impl<T> From<T> for T (the identity conversion), there is no #[derive] macro available (used for other "automatic" implementations), and no other macro that I'm aware of exists (though you could probably make one without much fuss if you really wanted it).

Upvotes: 7

Related Questions