Skip to main content

TryMapFrom

Derive Macro TryMapFrom 

Source
#[derive(TryMapFrom)]
{
    // Attributes available to this derive:
    #[try_map_from]
    #[map]
}
Expand description

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