#macro-derive #proc-macro #convert #struct #generate #try #target

macro derive-try-from-ref

A derive macro to generate TryFrom<&T> implementation

1 unstable release

0.1.0 Jan 17, 2024

#65 in #try

Download history 23/week @ 2024-07-20 74/week @ 2024-07-27 53/week @ 2024-08-03 34/week @ 2024-08-10 2/week @ 2024-08-17 15/week @ 2024-08-24 12/week @ 2024-08-31 2/week @ 2024-09-07 23/week @ 2024-09-14 29/week @ 2024-09-21 13/week @ 2024-09-28 40/week @ 2024-10-05 78/week @ 2024-10-12 18/week @ 2024-10-19 14/week @ 2024-10-26 32/week @ 2024-11-02

143 downloads per month
Used in 3 crates (via odra-macros)

MIT license

16KB
230 lines

Crates.io License: MIT

Description

This crate provides a proc macro to implement TryFrom<&Struct> for a target struct. It helps to convert a bigger struct to a few smaller, more specialized structs. The macro expands to a TryFrom implementation that tries to convert each field of the target struct from the whole source struct. If the conversion fails, the macro returns an error.

Usage

use try_from_ref::TryFromRef;

struct Source {
    x: u32,
    y: u32,
    name: String,
    description: String,
}

#[derive(derive_try_from::TryFromRef)]
#[source(Source)]
#[err(&'static str)]
struct Target {
    sum: Sum,
    meta: Metadata,
    #[default]
    is_dirty: bool,
}

expands to

#[automatically_derived]
impl ::core::convert::TryFrom<&'_ Source> for Target {
    type Error = &'static str;
    fn try_from(input: &'_ Source) -> ::core::result::Result<Self, Self::Error> {
        Ok(Self {
            sum: input.try_into()?,
            meta: input.try_into()?,
            is_dirty: Default::default(),
        })
    }
}

At the struct level, two attributes are required:

  • #[source(SourceType)] - the name of the source struct
  • #[err(ErrorType)] - the error type to return if the conversion fails

At the field level, another two attributes are supported:

  • #[default] - skips conversion, sets the default value of the type instead
  • #[expr(expression)] - the expression to evaluate to get the value of the field

MSRV (Minimum Supported Rust Version)

The minimum supported Rust version is 1.60.0.

Dependencies

~310–780KB
~18K SLoC