]> git.lizzy.rs Git - rust.git/blob - src/doc/style-guide/src/items.md
Rollup merge of #104967 - willcrichton:fix-scrape-examples, r=notriddle
[rust.git] / src / doc / style-guide / src / items.md
1 ## Items
2
3 `extern crate` statements must be first in a file. They must be ordered
4 alphabetically.
5
6 `use` statements, and module *declarations* (`mod foo;`, not `mod { ... }`)
7 must come before other items. We recommend that imports come before module
8 declarations; if imports and modules are separated, then they should be ordered
9 alphabetically. When sorting, `self` and `super` must come before any other
10 names. Module declarations should not be moved if they are annotated with
11 `#[macro_use]`, since that may be semantics changing.
12
13 Tools should make the above ordering optional.
14
15
16 ### Function definitions
17
18 In Rust, one finds functions by searching for `fn [function-name]`; It's
19 important that you style your code so that it's very searchable in this way.
20
21 The proper ordering and spacing is:
22
23 ```rust
24 [pub] [unsafe] [extern ["ABI"]] fn foo(arg1: i32, arg2: i32) -> i32 {
25     ...
26 }
27 ```
28
29 Avoid comments within the signature itself.
30
31 If the function signature does not fit on one line, then break after the opening
32 parenthesis and before the closing parenthesis and put each argument on its own
33 block-indented line. For example,
34
35 ```rust
36 fn foo(
37     arg1: i32,
38     arg2: i32,
39 ) -> i32 {
40     ...
41 }
42 ```
43
44 Note the trailing comma on the last argument.
45
46
47 ### Tuples and tuple structs
48
49 Write the type list as you would a parameter list to a function.
50
51 Build a tuple or tuple struct as you would call a function.
52
53 #### Single-line
54
55 ```rust
56 struct Bar(Type1, Type2);
57
58 let x = Bar(11, 22);
59 let y = (11, 22, 33);
60 ```
61
62 ### Enums
63
64 In the declaration, put each variant on its own line, block indented.
65
66 Format each variant accordingly as either a struct, tuple struct, or identifier,
67 which doesn't require special formatting (but without the `struct` keyword.
68
69 ```rust
70 enum FooBar {
71     First(u32),
72     Second,
73     Error {
74         err: Box<Error>,
75         line: u32,
76     },
77 }
78 ```
79
80 If a struct variant is [*small*](index.html#small-items), it may be formatted on
81 one line. In this case, do not use a trailing comma for the field list, but do
82 put spaces around each brace:
83
84 ```rust
85 enum FooBar {
86     Error { err: Box<Error>, line: u32 },
87 }
88 ```
89
90 In an enum with multiple struct variants, if any struct variant is written on
91 multiple lines, then the multi-line formatting should be used for all struct
92 variants. However, such a situation might be an indication that you should
93 factor out the fields of the variant into their own struct.
94
95
96 ### Structs and Unions
97
98 Struct names follow on the same line as the `struct` keyword, with the opening
99 brace on the same line when it fits within the right margin. All struct fields
100 are indented once and end with a trailing comma. The closing brace is not
101 indented and appears on its own line.
102
103 ```rust
104 struct Foo {
105     a: A,
106     b: B,
107 }
108 ```
109
110 If and only if the type of a field does not fit within the right margin, it is
111 pulled down to its own line and indented again.
112
113 ```rust
114 struct Foo {
115     a: A,
116     long_name:
117         LongType,
118 }
119 ```
120
121 Prefer using a unit struct (e.g., `struct Foo;`) to an empty struct (e.g.,
122 `struct Foo();` or `struct Foo {}`, these only exist to simplify code
123 generation), but if you must use an empty struct, keep it on one line with no
124 space between the braces: `struct Foo;` or `struct Foo {}`.
125
126 The same guidelines are used for untagged union declarations.
127
128 ```rust
129 union Foo {
130     a: A,
131     b: B,
132     long_name:
133         LongType,
134 }
135 ```
136
137
138 ### Tuple structs
139
140 Put the whole struct on one line if possible. Types in the parentheses should be
141 separated by a comma and space with no trailing comma. No spaces around the
142 parentheses or semi-colon:
143
144 ```rust
145 pub struct Foo(String, u8);
146 ```
147
148 Prefer unit structs to empty tuple structs (these only exist to simplify code
149 generation), e.g., `struct Foo;` rather than `struct Foo();`.
150
151 For more than a few fields, prefer a proper struct with named fields. Given
152 this, a tuple struct should always fit on one line. If it does not, block format
153 the fields with a field on each line and a trailing comma:
154
155 ```rust
156 pub struct Foo(
157     String,
158     u8,
159 );
160 ```
161
162
163 ### Traits
164
165 Trait items should be block-indented. If there are no items, the trait may be
166 formatted on a single line. Otherwise there should be line-breaks after the
167 opening brace and before the closing brace:
168
169 ```rust
170 trait Foo {}
171
172 pub trait Bar {
173     ...
174 }
175 ```
176
177 If the trait has bounds, there should be a space after the colon but not before
178 and before and after each `+`, e.g.,
179
180 ```rust
181 trait Foo: Debug + Bar {}
182 ```
183
184 Prefer not to line-break in the bounds if possible (consider using a `where`
185 clause). Prefer to break between bounds than to break any individual bound. If
186 you must break the bounds, put each bound (including the first) on its own
187 block-indented line, break before the `+` and put the opening brace on its own
188 line:
189
190 ```rust
191 pub trait IndexRanges:
192     Index<Range<usize>, Output=Self>
193     + Index<RangeTo<usize>, Output=Self>
194     + Index<RangeFrom<usize>, Output=Self>
195     + Index<RangeFull, Output=Self>
196 {
197     ...
198 }
199 ```
200
201
202 ### Impls
203
204 Impl items should be block indented. If there are no items, the impl may be
205 formatted on a single line. Otherwise there should be line-breaks after the
206 opening brace and before the closing brace:
207
208 ```rust
209 impl Foo {}
210
211 impl Bar for Foo {
212     ...
213 }
214 ```
215
216 Avoid line-breaking in the signature if possible. If a line break is required in
217 a non-inherent impl, break immediately before `for`, block indent the concrete type
218 and put the opening brace on its own line:
219
220 ```rust
221 impl Bar
222     for Foo
223 {
224     ...
225 }
226 ```
227
228
229 ### Extern crate
230
231 `extern crate foo;`
232
233 Use spaces around keywords, no spaces around the semi-colon.
234
235
236 ### Modules
237
238 ```rust
239 mod foo {
240 }
241 ```
242
243 ```rust
244 mod foo;
245 ```
246
247 Use spaces around keywords and before the opening brace, no spaces around the
248 semi-colon.
249
250 ### macro\_rules!
251
252 Use `{}` for the full definition of the macro.
253
254 ```rust
255 macro_rules! foo {
256 }
257 ```
258
259
260 ### Generics
261
262 Prefer to put a generics clause on one line. Break other parts of an item
263 declaration rather than line-breaking a generics clause. If a generics clause is
264 large enough to require line-breaking, you should prefer to use a `where` clause
265 instead.
266
267 Do not put spaces before or after `<` nor before `>`. Only put a space after `>`
268 if it is followed by a word or opening brace, not an opening parenthesis. There
269 should be a space after each comma and no trailing comma.
270
271 ```rust
272 fn foo<T: Display, U: Debug>(x: Vec<T>, y: Vec<U>) ...
273
274 impl<T: Display, U: Debug> SomeType<T, U> { ...
275 ```
276
277 If the generics clause must be formatted across multiple lines, each parameter
278 should have its own block-indented line, there should be newlines after the
279 opening bracket and before the closing bracket, and the should be a trailing
280 comma.
281
282 ```rust
283 fn foo<
284     T: Display,
285     U: Debug,
286 >(x: Vec<T>, y: Vec<U>) ...
287 ```
288
289 If an associated type is bound in a generic type, then there should be spaces on
290 either side of the `=`:
291
292 ```rust
293 <T: Example<Item = u32>>
294 ```
295
296 Prefer to use single-letter names for generic parameters.
297
298
299 ### `where` clauses
300
301 These rules apply for `where` clauses on any item.
302
303 A `where` clause may immediately follow a closing bracket of any kind.
304 Otherwise, it must start a new line, with no indent. Each component of a `where`
305 clause must be on its own line and be block indented. There should be a trailing
306 comma, unless the clause is terminated with a semicolon. If the `where` clause
307 is followed by a block (or assignment), the block should be started on a new
308 line. Examples:
309
310 ```rust
311 fn function<T, U>(args)
312 where
313     T: Bound,
314     U: AnotherBound,
315 {
316     body
317 }
318
319 fn foo<T>(
320     args
321 ) -> ReturnType
322 where
323     T: Bound,
324 {
325     body
326 }
327
328 fn foo<T, U>(
329     args,
330 ) where
331     T: Bound,
332     U: AnotherBound,
333 {
334     body
335 }
336
337 fn foo<T, U>(
338     args
339 ) -> ReturnType
340 where
341     T: Bound,
342     U: AnotherBound;  // Note, no trailing comma.
343
344 // Note that where clauses on `type` aliases are not enforced and should not
345 // be used.
346 type Foo<T>
347 where
348     T: Bound
349 = Bar<T>;
350 ```
351
352 If a `where` clause is very short, we recommend using an inline bound on the
353 type parameter.
354
355
356 If a component of a `where` clause is long, it may be broken before `+` and
357 further block indented. Each bound should go on its own line. E.g.,
358
359 ```rust
360 impl<T: ?Sized, Idx> IndexRanges<Idx> for T
361 where
362     T: Index<Range<Idx>, Output = Self::Output>
363         + Index<RangeTo<Idx>, Output = Self::Output>
364         + Index<RangeFrom<Idx>, Output = Self::Output>
365         + Index<RangeInclusive<Idx>, Output = Self::Output>
366         + Index<RangeToInclusive<Idx>, Output = Self::Output> + Index<RangeFull>
367 ```
368
369 #### Option - `where_single_line`
370
371 `where_single_line` is `false` by default. If `true`, then a where clause with
372 exactly one component may be formatted on a single line if the rest of the
373 item's signature is also kept on one line. In this case, there is no need for a
374 trailing comma and if followed by a block, no need for a newline before the
375 block. E.g.,
376
377 ```rust
378 // May be single-lined.
379 fn foo<T>(args) -> ReturnType
380 where T: Bound {
381     body
382 }
383
384 // Must be multi-lined.
385 fn foo<T>(
386     args
387 ) -> ReturnType
388 where
389     T: Bound,
390 {
391     body
392 }
393 ```
394
395
396 ### Type aliases
397
398 Type aliases should generally be kept on one line. If necessary to break the
399 line, do so after the `=`; the right-hand-side should be block indented:
400
401 ```rust
402 pub type Foo = Bar<T>;
403
404 // If multi-line is required
405 type VeryLongType<T, U: SomeBound> =
406     AnEvenLongerType<T, U, Foo<T>>;
407 ```
408
409 Where possible avoid `where` clauses and keep type constraints inline. Where
410 that is not possible split the line before and after the `where` clause (and
411 split the `where` clause as normal), e.g.,
412
413 ```rust
414 type VeryLongType<T, U>
415 where
416     T: U::AnAssociatedType,
417     U: SomeBound,
418 = AnEvenLongerType<T, U, Foo<T>>;
419 ```
420
421
422 ### Associated types
423
424 Associated types should follow the guidelines above for type aliases. Where an
425 associated type has a bound, there should be a space after the colon but not
426 before:
427
428 ```rust
429 pub type Foo: Bar;
430 ```
431
432
433 ### extern items
434
435 When writing extern items (such as `extern "C" fn`), always be explicit about
436 the ABI. For example, write `extern "C" fn foo ...`, not `extern fn foo ...`, or
437 `extern "C" { ... }`.
438
439
440 ### Imports (`use` statements)
441
442 If an import can be formatted on one line, do so. There should be no spaces
443 around braces.
444
445 ```rust
446 use a::b::c;
447 use a::b::d::*;
448 use a::b::{foo, bar, baz};
449 ```
450
451
452 #### Large list imports
453
454 Prefer to use multiple imports rather than a multi-line import. However, tools
455 should not split imports by default (they may offer this as an option).
456
457 If an import does require multiple lines (either because a list of single names
458 does not fit within the max width, or because of the rules for nested imports
459 below), then break after the opening brace and before the closing brace, use a
460 trailing comma, and block indent the names.
461
462
463 ```rust
464 // Prefer
465 foo::{long, list, of, imports};
466 foo::{more, imports};
467
468 // If necessary
469 foo::{
470     long, list, of, imports, more,
471     imports,  // Note trailing comma
472 };
473 ```
474
475
476 #### Ordering of imports
477
478 A *group* of imports is a set of imports on the same or sequential lines. One or
479 more blank lines or other items (e.g., a function) separate groups of imports.
480
481 Within a group of imports, imports must be sorted ascii-betically. Groups of
482 imports must not be merged or re-ordered.
483
484
485 E.g., input:
486
487 ```rust
488 use d;
489 use c;
490
491 use b;
492 use a;
493 ```
494
495 output:
496
497 ```rust
498 use c;
499 use d;
500
501 use a;
502 use b;
503 ```
504
505 Because of `macro_use`, attributes must also start a new group and prevent
506 re-ordering.
507
508 Note that tools which only have access to syntax (such as Rustfmt) cannot tell
509 which imports are from an external crate or the std lib, etc.
510
511
512 #### Ordering list import
513
514 Names in a list import must be sorted ascii-betically, but with `self` and
515 `super` first, and groups and glob imports last. This applies recursively. For
516 example, `a::*` comes before `b::a` but `a::b` comes before `a::*`. E.g.,
517 `use foo::bar::{a, b::c, b::d, b::d::{x, y, z}, b::{self, r, s}};`.
518
519
520 #### Normalisation
521
522 Tools must make the following normalisations:
523
524 * `use a::self;` -> `use a;`
525 * `use a::{};` -> (nothing)
526 * `use a::{b};` -> `use a::b;`
527
528 And must apply these recursively.
529
530 Tools must not otherwise merge or un-merge import lists or adjust glob imports
531 (without an explicit option).
532
533
534 #### Nested imports
535
536 If there are any nested imports in a list import, then use the multi-line form,
537 even if the import fits on one line. Each nested import must be on its own line,
538 but non-nested imports must be grouped on as few lines as possible.
539
540 For example,
541
542 ```rust
543 use a::b::{
544     x, y, z,
545     u::{...},
546     w::{...},
547 };
548 ```
549
550
551 #### Merging/un-merging imports
552
553 An example:
554
555 ```rust
556 // Un-merged
557 use a::b;
558 use a::c::d;
559
560 // Merged
561 use a::{b, c::d};
562 ```
563
564 Tools must not merge or un-merge imports by default. They may offer merging or
565 un-merging as an option.