iter_convertable

Attribute Macro iter_convertable 

Source
#[iter_convertable]
Expand description

Attribute for structs that can be built from an iterator. This attribute must be attached to a struct definition

§Argument

The argument passed to the attribute must be a type, and each unique type of the fields in the target struct must implement From or TryFrom the passed type

§Effects

This attribute implements the trait structinator_traits::SpecifyCreatableStruct with InnerIteratorType set to the argument passed to this attribute.

The generated function, create_struct, will be implemented using a HashMap<String,InnerIteratorType>, which will store the first N values from the iterator, where N is the number of fields in the struct this attribute is attached to, and then be assign the values in that HashMap to corresponding fields in the struct, as determined by a stringification of the field’s name.

The passed value will then be unwrapped from the InnerIteratorType to the type of the struct, panicking if the conversion fails.

In other words, if the field definition looks like this:

value_name: u16,

Then the corresponding field in the struct literal generated by create_struct would look something like this (with error messages removed)

value_name = <u16 as TryFrom>::try_from(hash_map.remove("value_name").unwrap()).unwrap(),

§Panics

This attribute will cause a panic if attached to anything other than a struct definition

This attribute will implement SpecifyCreatableStruct in a manner that assumes the InnerIteratorType implements TryFrom for each unique type used in the fields of the target struct

If InnerIteratorType’s type does not implement TryFrom, or the conversion fails, this function will panic. The recomended way to make sure TryFrom is always implemented, minimizing panics to only when the conversion itself fails, is to create an enum specifically for this purpose, with unique variants for each unique type used by the fields of the target struct, and add the attribute unique_try_froms() to said enum. See enum_unwrapper’s documentation for detailed instructions on how to do so.

The function will also panic if the Iterator argument yields NamedFields with identical name values before providing enough values to fill the target struct.

§Errors

The generated implementation returns an Err containing a &'static str if the supplied Iterator returns None before yielding enough values to fill the target struct.

§More Info

See SpecifyCreatableStruct documentation for more information & examples.