derive-ctor
derive-ctor is a Rust procedural macro crate that allows you to easily generate constructor methods for your structs. With the #[derive(ctor)] attribute, you can automatically create a constructor for all fields in the struct. The crate also provides various options to customize the generated constructor methods.
Features
- Automatically generate a constructor method for all fields in a struct with
#[derive(ctor)]. - Customize the name and visibility of the auto-generated constructor using
#[ctor(visibility method_name)]. - Provide a list of names to generate multiple constructors.
- Customize field behavior in the constructor with the following attributes:
#[ctor(default)]- Exclude the field from the generated method and use its default value.#[ctor(value(EXPRESSION))]- Exclude the field from the generated method and use the defined expression as its default value.#[ctor(method(METHOD_NAME))]- Exclude the field from the generated method and call the defined method for its default value.#[ctor(impl)]- Change the parameter type for the generated method toimpl Into<Type>.
Basic Usage
Add derive-ctor to your Cargo.toml:
[]
= "0.1"
Import the crate in your Rust code:
use ctor;
Annotate your struct with #[derive(ctor)] to automatically generate a new constructor:
let my_struct = new;
Configurations
You can modify the name and visibility of the generated method, and define additional
constructors by using the #[ctor] attribute on the target struct after ctor is derived.
In the following example, three constructor methods are created: new, with_defaults, and internal.
These methods all inherit their respective visibilities defined within the #[ctor] attribute.
Field Configurations
Fields can also be annotated with #[ctor(PROPERTY)] to change their behaviour in the generated methods.
The following are the available properties that can be used with the field-attributes
#[ctor(default)] - This property excludes the annotated field from the constructor and uses its default value.
let my_struct = new;
#[ctor(impl)] - This property modifies the parameter type of the annotated field for the generated method
converting it from Type -> impl Into<Type>.
let my_struct = new;
#[ctor(value(VALUE))] - This property excludes the annotated field from the constructor and utilizes the defined expression
to generate its value.
let my_struct = new; // generates MyStruct { field1: 100, field2: "foo" }
#[ctor(method(METHOD_NAME)] - This property exludes the annotated field from the constructor and invokes the provided
method to generate its value.
let my_struct = new;
Advanced Configuration
Field attributes can additionally be configured with a list of indices corresponding to the methods to use the generated value for. This allows for the creation of multiple functions with different parameter requirements.
let my_struct1 = new;
let my_struct2 = with_defaults;