简体   繁体   中英

How does one map a struct to another one in 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 !

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

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