Optionable

Derive Macro Optionable 

Source
#[derive(Optionable)]
{
    // Attributes available to this derive:
    #[optionable]
    #[optionable_attr]
}
Available on crate feature derive only.
Expand description

Derive macro to derive the Optionable trait for structs/enums recursively by generating a type with all fields recursively replaced with Option versions. All non-required fields have to implement the Optionable trait. This trait is already implemented by this library for many primitive types, wrapper and container types.

§Type-level attributes (on the struct/enum level)

  • optionable_attr: Helper for the derive type-level attribute, for details see the derive attribute.
  • derive: Allows to specify derive attributes that should be attached to the generate optioned struct/enum. If you need to forward additional helper attributes to the generated type use optionable_attr with the attribute to forward as content (works for type and field attributes).
    #[derive(optionable)]
    #[optionable(derive(Deserialize, Serialize))]
    #[optionable_attr(serde(rename_all = "camelCase"))]
    struct MyStruct{
      #[optionable_attr(serde(rename = "firstName"))]
      name: String,
      surname: String,
    }
  • no_convert: Does not derive the OptionableConvert implementation. Might be required if the target type involves smart pointers or unsized fields.
    #[derive(optionable)]
    #[optionable(no_convert)]
    struct MyStruct{}
  • suffix: The name of the generated optioned struct/enum will be <original><suffix> with suffix defaulting to "Opt". The suffix value can be adjusted via e.g. #[optionable(suffix="Ac")].
    #[derive(optionable)]
    #[optionable(suffix="Ac")]
    struct MyStruct{}

§Field-level attributes (for structs and struct-typed enum variants)

  • optionable_attr: Helper for the derive type-level attribute, for details see the derive attribute.
  • required: The annotated field will be kept as is and won’t be transformed into some optional variant for the derived optioned Struct.
    #[derive(optionable)]
    struct MyStruct{
      street: String; // will be an `Option<String>` in the derived `MyStructOpt`.
      #[optionable(required)]
      number: u32; // will also be a u32 in the derived `MyStructOpt`.
    }