'Copy identical fields of different struct in rust [duplicate]

Let's suppose we have two structs with identical fields (and types).

struct A {
  pub data1: i32;
  pub data2: string;
}

struct B {
  pub data1: i32;
  pub data2: string;
}

To copy the struct A and B, I have to do

fn convert_A_to_B(a: A) -> B {
  B {
    data1: a.data1,
    data2: a.data2
  }
}

I wish I can do something like

B {
  ..a
}

but it's not possible since types are different. Is there any macro or syntax that do the simple move of all identical fields?



Solution 1:[1]

If you are sure of the struct memory layout is the same you can use std::mem::transmute:

#[repr(C)]
#[derive(Debug)]
struct A {
  pub data1: i32,
  pub data2: String
}

#[repr(C)]
struct B {
  pub data1: i32,
  pub data2: String
}

impl From<B> for A {
    fn from(b: B) -> A {
        unsafe { std::mem::transmute(b) }
    }
}

fn main() {
    let b = B {data1: 10, data2: "Foo".to_string()};
    let a: A = b.into();
    
    println!("{a:?}");
}

Playground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1