| 1 | # What `#[derive(Constructor)]` generates |
| 2 | |
| 3 | A common pattern in Rust is to create a static constructor method called |
| 4 | `new`. This method can then be used to create an instance of a struct. You |
| 5 | can now derive this method by using `#[derive(Constructor)]`, even though |
| 6 | `Constructor` is not an actual trait. The generated `new` method is very |
| 7 | similar to the `from` method when deriving `From`, except that it takes multiple |
| 8 | arguments instead of a tuple. |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | ## Tuple structs |
| 14 | |
| 15 | When deriving `Constructor` for a tuple struct with two fields like this: |
| 16 | |
| 17 | ```rust |
| 18 | # use derive_more::Constructor; |
| 19 | # |
| 20 | #[derive(Constructor)] |
| 21 | struct MyInts(i32, i32); |
| 22 | ``` |
| 23 | |
| 24 | Code like this will be generated: |
| 25 | |
| 26 | ```rust |
| 27 | # struct MyInts(i32, i32); |
| 28 | impl MyInts { |
| 29 | pub const fn new(__0: i32, __1: i32) -> MyInts { |
| 30 | MyInts(__0, __1) |
| 31 | } |
| 32 | } |
| 33 | ``` |
| 34 | |
| 35 | The generated code is similar for more or less fields. |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | ## Regular structs |
| 41 | |
| 42 | For regular structs almost the same code is generated as for tuple structs |
| 43 | except that it assigns the fields differently. |
| 44 | |
| 45 | ```rust |
| 46 | # use derive_more::Constructor; |
| 47 | # |
| 48 | #[derive(Constructor)] |
| 49 | struct Point2D { |
| 50 | x: i32, |
| 51 | y: i32, |
| 52 | } |
| 53 | ``` |
| 54 | |
| 55 | Code like this will be generated: |
| 56 | |
| 57 | ```rust |
| 58 | # struct Point2D { |
| 59 | # x: i32, |
| 60 | # y: i32, |
| 61 | # } |
| 62 | impl Point2D { |
| 63 | pub const fn new(x: i32, y: i32) -> Point2D { |
| 64 | Point2D { x: x, y: y } |
| 65 | } |
| 66 | } |
| 67 | ``` |
| 68 | |
| 69 | The generated code is similar for more or less fields. |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | ## Enums |
| 75 | |
| 76 | Currently `Constructor` cannot be derived for enums. This is because the `new` |
| 77 | method might then need to have a different number of arguments. This is |
| 78 | currently not supported by Rust. So this functionality will not be added until |
| 79 | this [RFC](https://github.com/rust-lang/rfcs/issues/376) (or a similar one) is |
| 80 | accepted and implemented. |