Skip to content

Commit 9c285b0

Browse files
committed
Style: default over new
1 parent 84d6cde commit 9c285b0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

docs/dev/style.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,31 @@ impl Person {
186186
}
187187
```
188188

189+
## Constructors
190+
191+
Prefer `Default` to zero-argument `new` function
192+
193+
```rust
194+
// Good
195+
#[derive(Default)]
196+
struct Foo {
197+
bar: Option<Bar>
198+
}
199+
200+
// Not as good
201+
struct Foo {
202+
bar: Option<Bar>
203+
}
204+
205+
impl Foo {
206+
fn new() -> Foo {
207+
Foo { bar: None }
208+
}
209+
}
210+
```
211+
212+
Prefer `Default` even it has to be implemented manually.
213+
189214
## Avoid Monomorphization
190215

191216
Rust uses monomorphization to compile generic code, meaning that for each instantiation of a generic functions with concrete types, the function is compiled afresh, *per crate*.

0 commit comments

Comments
 (0)