Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 203
Test Avatar asked Oct 29 '25 09:10

Test


1 Answers

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).

like image 156
kmdreko Avatar answered Oct 31 '25 00:10

kmdreko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!