diff options
Diffstat (limited to 'docs')
-rw-r--r-- | docs/dev/style.md | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/docs/dev/style.md b/docs/dev/style.md index 59067d234..20f1b6253 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*. |
@@ -223,6 +248,8 @@ fn frbonicate(f: impl AsRef<Path>) { | |||
223 | 248 | ||
224 | # Premature Pessimization | 249 | # Premature Pessimization |
225 | 250 | ||
251 | ## Avoid Allocations | ||
252 | |||
226 | Avoid writing code which is slower than it needs to be. | 253 | Avoid writing code which is slower than it needs to be. |
227 | Don't allocate a `Vec` where an iterator would do, don't allocate strings needlessly. | 254 | Don't allocate a `Vec` where an iterator would do, don't allocate strings needlessly. |
228 | 255 | ||
@@ -242,6 +269,8 @@ if words.len() != 2 { | |||
242 | } | 269 | } |
243 | ``` | 270 | ``` |
244 | 271 | ||
272 | ## Push Allocations to the Call Site | ||
273 | |||
245 | If allocation is inevitable, let the caller allocate the resource: | 274 | If allocation is inevitable, let the caller allocate the resource: |
246 | 275 | ||
247 | ```rust | 276 | ```rust |
@@ -257,6 +286,9 @@ fn frobnicate(s: &str) { | |||
257 | } | 286 | } |
258 | ``` | 287 | ``` |
259 | 288 | ||
289 | This is better because it reveals the costs. | ||
290 | It is also more efficient when the caller already owns the allocation. | ||
291 | |||
260 | ## Collection types | 292 | ## Collection types |
261 | 293 | ||
262 | Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`. | 294 | Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`. |