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