1 # A custom derive implementation for `#[derive(new)]`
3 A `derive(new)` attribute creates a `new` constructor function for the annotated
4 type. That function takes an argument for each field in the type giving a
5 trivial constructor. This is useful since as your type evolves you can make the
6 constructor non-trivial (and add or remove fields) without changing client code
7 (i.e., without breaking backwards compatibility). It is also the most succinct
8 way to initialise a struct or an enum.
10 Implementation uses macros 1.1 custom derive (which works in stable Rust from
13 `#[no_std]` is fully supported if you switch off the default feature `"std"`.
28 extern crate derive_new;
31 Generating constructor for a simple struct:
40 let _ = Bar::new(42, "Hello".to_owned());
43 Default values can be specified either via `#[new(default)]` attribute which removes
44 the argument from the constructor and populates the field with `Default::default()`,
45 or via `#[new(value = "..")]` which initializes the field with a given expression:
57 let _ = Foo::new(true);
60 Generic types are supported; in particular, `PhantomData<T>` fields will be not
61 included in the argument list and will be intialized automatically:
64 use std::marker::PhantomData;
67 struct Generic<'a, T: Default, P> {
74 let _ = Generic::<i32, u8>::new("Hello");
77 For enums, one constructor method is generated for each variant, with the type
78 name being converted to snake case; otherwise, all features supported for
79 structs work for enum variants as well:
85 SecondVariant(bool, #[new(default)] u8),
86 ThirdVariant { x: i32, #[new(value = "vec![1]")] y: Vec<u8> }
89 let _ = Enum::new_first_variant();
90 let _ = Enum::new_second_variant(true);
91 let _ = Enum::new_third_variant(42);