How does one map a struct to another one in Rust?

Viewed 3053

In others languages (like Java), libraries are available for mapping object fields to another object (like mapstruct). It is useful indeed for isolating controller and service from each other.

PersonDto personDto = mapper.businessToDto(personBusiness);

And I can't find how to do it with Rust ? I didn't find any libraries helping with this, or any way to do it. Any resource would be very appreciated !

1 Answers

In rust you usually do it via From trait:

struct Person {
  name: String,
  age: u8,
}

struct PersonDto {
  name: String,
  age: u64,
}

impl From<Person> for PersonDto {
  fn from(p: Person) -> Self {
    Self {
      name: p.name,
      age: p.age.into(),
    }
  }
}

So you can make an Into conversion:

let person = Person { name: "Alex".to_string(), age: 42 };

let person_dto: PersonDto = person.into();
// or via an explicit `T::from:
let person_dto = PersonDto::from(person);
Related