From 9c285b0341fcf5ce9e15821da20727a313624497 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Wed, 14 Oct 2020 20:02:03 +0200 Subject: Style: default over new --- docs/dev/style.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'docs/dev/style.md') diff --git a/docs/dev/style.md b/docs/dev/style.md index 59067d234..435de63e3 100644 --- a/docs/dev/style.md +++ b/docs/dev/style.md @@ -186,6 +186,31 @@ impl Person { } ``` +## Constructors + +Prefer `Default` to zero-argument `new` function + +```rust +// Good +#[derive(Default)] +struct Foo { + bar: Option +} + +// Not as good +struct Foo { + bar: Option +} + +impl Foo { + fn new() -> Foo { + Foo { bar: None } + } +} +``` + +Prefer `Default` even it has to be implemented manually. + ## Avoid Monomorphization 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*. -- cgit v1.2.3