bachrc
bachrc

Reputation: 1196

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 !

Upvotes: 8

Views: 8173

Answers (2)

Artem Romanenia
Artem Romanenia

Reputation: 69

In a comment, author of the question mentioned 'avoiding fastidious hand mapping' as part of their question. Rust crate o2o (which I am the author of) tries to deal specifically with this problem:

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

#[derive(o2o)]
#[o2o(from_owned(Person))]
struct PersonDto {
  name: String,
  #[o2o(as_type(u8))]
  age: u64,
}

This will generate following code automatically:

impl std::convert::From<Person> for PersonDto {
    fn from(value: Person) -> PersonDto {
        PersonDto {
            name: value.name,
            age: value.age as u64,
        }
    }
}

It can generate implementations for From, Into and custom IntoExisting traits for structs, tuple structs, tuples, and can handle cases like mismatching field names, types, skipping fields, nested structs, nested collections, 'uneven' structs, wrapping structs etc. It is also designed to be applicable on any side of the mapping.

Upvotes: 3

Kitsu
Kitsu

Reputation: 3435

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

Upvotes: 22

Related Questions