from-similar

FromSimilar automatically implements From between two structs that are “similar”.
Specifically for structs where the fields have the same names. Or tuple structs with similar positional arguments.
This macro is mainly useful to generate predicable From implementations for:
- Structs that are mostly identical, except for a few attributes like
#[serde]exceptions for serializing BSON. - Structs with a subset of fields from the more complete one.
Struct attributes
#[from(InputType)] a required attribute to specify the input type.
Will generate impl From<InputType> for T.
#[from(.., bidirectional = true)] optional attribute to implement both directions.
Will generate impl From<InputType> for T and impl From<T> for InputType.
Field attributes
#[use_into] is an optional field attribute to use .into() when converting this field.
#[use_into_option] for Option<T> types that need a .map(Into::into) when converting this field.
#[use_into_collection] for impl IntoIterator<T> types that should map each item and collect.
Example with database models
A bidirectional FromSimilar that can be used for MongoDB.
use FromSimilar;
let normal = default;
let db: DatabaseModel = normal.into;
let _: NormalModel = db.into;
Example with views
Note: #[from(.., bidirectional = true)] would break here, because it’s a lossy conversion.
use FromSimilar;
let full = default;
let _: PublicView = full.into;
Example with tuple struct
use FromSimilar;
;
;
let mut data = default;
data.0 += "Pushing ";
data.0 += "some text";
data.1 = 42;
let data: SealedData = data.into;