Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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 !

like image 923
bachrc Avatar asked Jun 25 '20 12:06

bachrc


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);
like image 76
Kitsu Avatar answered Oct 17 '22 15:10

Kitsu