Custom Attrs
A library allowing you to do things with your variant fields.
Installation and Usage
Add this to your Cargo.toml
file :
[]
= "1.6"
Then you can use the derive
attribute to use the library.
use CustomAttrs;
Attribute declaration.
Each attribute declaration goes between the derive and the enum.
use CustomAttrs;
// attribute declarations
By default, an attribute declaration is composed of two parts : an attribute's name and it's type.
You can declare many attribute declarations in a single attr
.
Optionally, you can add more components.
Optional components
You can set the visibility before the attribute name. This will change the visibility of the getter function.
By default, each attribute declared require a value to be set for each variant. If this requirement is not set, the library will produce an error.
You can disable this behavior by making it optional, by writing type into an Option
, or by adding a default value behind the attribute declaration. See the example below.
Optional attribute syntax :
With default value syntax :
You can add documentation to attributes declaration. It will be added to the getter function.
Setting a value
To set a value for a variant, just add the name of the attribute followed by the value you want to set.
Like declarations, you can set many values at once.
If the attribute is optional, you don't have to wrap it in a Some
. custom_attrs
will do this for you (value wrapped in a Some are still supported). If you want the value to be None
, just put None
behind the it.
Self References
In attribute values you set, you can add a reference to a field of the variant.
The syntax is the following :
Self references are processed before the value is parsed as expression, so you can use them anywhere you need :
If you're using self reference, the value returned will also be a reference. You can deref it like so :
Attribute configuration
You can configure you attributes to change their characteristics.
The syntax of a property is the following :
Configs can also be flags:
Like attributes, you can define many properties in one bloc or add many config blocs.
Here is a list of all the properties :
function
: defines the name of the function to get the attribute
Getting a value attribute
To get the value from a variant, simple call get_<attribute name>
or the name you've set in the properties of the attributes.
.get_a;
VariantA
The type this function returns is defined in the attribute declaration.
If you've set a documentation on the attribute, it will be shown on this function.
Examples
use CustomAttrs;
// ...
See the examples directory for more details.
Features
help_span
: Merge main error and help notes, while these have they own span, and do not produce a separated error. This features is nightly only.
License
Licensed under the MIT license.