diff options
author | Aleksey Kladov <[email protected]> | 2020-10-14 19:02:03 +0100 |
---|---|---|
committer | Aleksey Kladov <[email protected]> | 2020-10-14 19:02:03 +0100 |
commit | 9c285b0341fcf5ce9e15821da20727a313624497 (patch) | |
tree | 2e73cabbf233019601f8f19c8c38625f10305ca8 | |
parent | 84d6cdef86dfe1054ecafaedfddbf90a2b3a469d (diff) |
Style: default over new
-rw-r--r-- | docs/dev/style.md | 25 |
1 files changed, 25 insertions, 0 deletions
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 { | |||
186 | } | 186 | } |
187 | ``` | 187 | ``` |
188 | 188 | ||
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 | |||
189 | ## Avoid Monomorphization | 214 | ## Avoid Monomorphization |
190 | 215 | ||
191 | 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*. | 216 | 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*. |