Struct Morph
macro for morphing one struct into another.
Installation
or manually
= "0.6"
Usage
I occasionally run into use case where i have two structs representing very similar data. They share most of the fields or can sometmes even be subset of one.
Say we have a struct ProductRow
coming from database and another struct ProductInfo
which is what will be sent as a json from the api.
now for this small when we need to convert ProductRows to ProductInfos we can manually do it, but for larger structs it becomes quite mechanical.
with this library you can write the following
use ;
and then you can simply generate a product info from a product row
let product_row: ProductRow = ProductRow ;
let product_info: ProductInfo = from;
This will copy the values for fields with same name (and type) and for the rest one can provide customer transform functions.
It does so by implementing a From
trait for the source and target struct.
There are 2 types field modifiers
- transform
this takes an transform function which takes &SourceStruct as a param and returns the correct type
- select
this takes a source field to replace the value for the field