A custom derive implementation for #[derive(new)]
A derive(new) attribute creates a new constructor function for the annotated
type. That function takes an argument for each field in the type giving a
trivial constructor. This is useful since as your type evolves you can make the
constructor non-trivial (and add or remove fields) without changing client code
(i.e., without breaking backwards compatibility). It is also the most succinct
way to initialise a struct or an enum.
Implementation uses macros 1.1 custom derive (which works in stable Rust from 1.15 onwards).
#[no_std] is fully supported if you switch off the default feature "std".
Examples
Cargo.toml:
[]
= "0.5"
Include the macro:
-
Rust Edition 2015
extern crate derive_new; -
Rust Edition 2018
use new;
Generating constructor for a simple struct:
let _ = new;
Default values can be specified either via #[new(default)] attribute which removes
the argument from the constructor and populates the field with Default::default(),
or via #[new(value = "..")] which initializes the field with a given expression:
let _ = new;
To make type conversion easier, #[new(into)] attribute changes the parameter type
to impl Into<T>, and populates the field with value.into():
let _ = new;
For iterators/collections, #[new(into_iter = "T")] attribute changes the parameter type
to impl IntoIterator<Item = T>, and populates the field with value.into_iter().collect():
let _ = new;
let _ = new;
Generic types are supported; in particular, PhantomData<T> fields will be not
included in the argument list and will be initialized automatically:
use PhantomData;
let _ = new;
For enums, one constructor method is generated for each variant, with the type name being converted to snake case; otherwise, all features supported for structs work for enum variants as well:
let _ = new_first_variant;
let _ = new_second_variant;
let _ = new_third_variant;