#[derive(TryMapFrom)]
{
// Attributes available to this derive:
#[try_map_from]
#[map]
}
Expand description
Derive macro that generates impl TryFrom<Source> for Target by mapping struct fields.
Use this when one or more field conversions can fail. The generated implementation
returns Result<Self, MapError>.
§Example
use struct_mapper::TryMapFrom;
use std::convert::TryInto;
struct RawInput {
count: i64,
name: String,
}
#[derive(TryMapFrom)]
#[try_map_from(RawInput)]
struct ValidInput {
#[map(try_into)]
count: u32,
name: String,
}
let raw = RawInput { count: 42, name: "Alice".into() };
let valid: ValidInput = raw.try_into().unwrap();
assert_eq!(valid.count, 42);
assert_eq!(valid.name, "Alice");§Field Attributes
All MapFrom attributes work here, plus:
| Attribute | Description |
|---|---|
#[map(try_into)] | Call .try_into() on the source value (fallible) |
#[map(try_with = "fn")] | Apply a fallible conversion function |
Derive macro that generates impl TryFrom<Source> for Target by mapping fields. |
Use this when one or more field conversions can fail (e.g., type narrowing,
parsing, validation). The generated implementation returns
Result<Self, struct_mapper::MapError>.
§Usage
ⓘ
use struct_mapper::TryMapFrom;
struct RawInput {
count: i64,
name: String,
}
#[derive(TryMapFrom)]
#[try_map_from(RawInput)]
struct ValidInput {
#[map(try_into)]
count: u32, // i64 -> u32 can fail
name: String, // direct (infallible)
}
// Now you can do:
let raw = RawInput { count: 42, name: "Alice".into() };
let valid: ValidInput = raw.try_into().unwrap();§Field Attributes
All MapFrom attributes work here, plus:
#[map(try_into)]— Call.try_into()on the source field (fallible)#[map(try_with = "path::to::fn")]— Apply a fallible conversion function