简体   繁体   中英

generic From implementation in Rust

I have two structs A and B that are exactly similar. I am trying to convert both A and B to another type C. The definitions of A,B and C are given below.

pub struct A {
   pub a: i32,
}

pub struct B {
   pub a: i32,
}

pub struct C {
   pub b: i32,
}

My implementation for converting from A to C is shown below:-

impl From<A> for C { 
  fn from(a: A) -> C {
    C {b: a.a}
  }
}

Since A and B both are similar, for converting from B to C, currently I have a duplicate implementation of the From defined above.

I am looking for a way to make the From implementation generic and only bounded to use A and B. My implementation here is as follows:-

trait Types {}

impl Types for A {}
impl Types for B {}

impl<T: Types> From<T> for C where T: Types {
    fn from(entity: T) -> C {
        C { b: entity.a }
    }
}

But when I compile a program with the code above, I get the following error,

error[E0609]: no field `a` on type `T`
   |
27 | impl<T: Types> From<T> for C where T: Types {
   |      - type parameter 'T' declared here

I would like to know a way to resolve this error since I have no other choice but to preserve A and B and avoid code duplication.

Usually this is done by macros:

macro_rules! to_C {
    ($t:ty) => {
        impl From<$t> for C { 
            fn from(a: $t) -> C {
              C{b: a.a}
            }
        }
    };
}

to_C!{A}
to_C!{B}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM