]> git.lizzy.rs Git - rust.git/blob - src/doc/style-guide/src/expressions.md
Rollup merge of #104024 - noeddl:unused-must-use, r=compiler-errors
[rust.git] / src / doc / style-guide / src / expressions.md
1 ## Expressions
2
3 ### Blocks
4
5 A block expression should have a newline after the initial `{` and before the
6 terminal `}`. Any qualifier before the block (e.g., `unsafe`) should always be
7 on the same line as the opening brace, and separated with a single space. The
8 contents of the block should be block indented:
9
10 ```rust
11 fn block_as_stmt() {
12     a_call();
13
14     {
15         a_call_inside_a_block();
16
17         // a comment in a block
18         the_value
19     }
20 }
21
22 fn block_as_expr() {
23     let foo = {
24         a_call_inside_a_block();
25
26         // a comment in a block
27         the_value
28     };
29 }
30
31 fn unsafe_block_as_stmt() {
32     a_call();
33
34     unsafe {
35         a_call_inside_a_block();
36
37         // a comment in a block
38         the_value
39     }
40 }
41 ```
42
43 If a block has an attribute, it should be on its own line:
44
45 ```rust
46 fn block_as_stmt() {
47     #[an_attribute]
48     {
49         #![an_inner_attribute]
50
51         // a comment in a block
52         the_value
53     }
54 }
55 ```
56
57 Avoid writing comments on the same line as the braces.
58
59 An empty block should be written as `{}`.
60
61 A block may be written on a single line if:
62
63 * it is either used in expression position (not statement position) or is an
64   unsafe block in statement position
65 * contains a single-line expression and no statements
66 * contains no comments
67
68 A single line block should have spaces after the opening brace and before the
69 closing brace.
70
71 Examples:
72
73 ```rust
74 fn main() {
75     // Single line
76     let _ = { a_call() };
77     let _ = unsafe { a_call() };
78
79     // Not allowed on one line
80     // Statement position.
81     {
82         a_call()
83     }
84
85     // Contains a statement
86     let _ = {
87         a_call();
88     };
89     unsafe {
90         a_call();
91     }
92
93     // Contains a comment
94     let _ = {
95         // A comment
96     };
97     let _ = {
98         // A comment
99         a_call()
100     };
101
102     // Multiple lines
103     let _ = {
104         a_call();
105         another_call()
106     };
107     let _ = {
108         a_call(
109             an_argument,
110             another_arg,
111         )
112     };
113 }
114 ```
115
116
117 ### Closures
118
119 Don't put any extra spaces before the first `|` (unless the closure is prefixed
120 by `move`); put a space between the second `|` and the expression of the
121 closure. Between the `|`s, you should use function definition syntax, however,
122 elide types where possible.
123
124 Use closures without the enclosing `{}`, if possible. Add the `{}` when you have
125 a return type, when there are statements, there are comments in the body, or the
126 body expression spans multiple lines and is a control-flow expression. If using
127 braces, follow the rules above for blocks. Examples:
128
129 ```rust
130 |arg1, arg2| expr
131
132 move |arg1: i32, arg2: i32| -> i32 {
133     expr1;
134     expr2
135 }
136
137 || Foo {
138     field1,
139     field2: 0,
140 }
141
142 || {
143     if true {
144         blah
145     } else {
146         boo
147     }
148 }
149
150 |x| unsafe {
151     expr
152 }
153 ```
154
155
156 ### Struct literals
157
158 If a struct literal is *small* it may be formatted on a single line. If not,
159 each field should be on it's own, block-indented line. There should be a
160 trailing comma in the multi-line form only. There should be a space after the
161 colon only.
162
163 There should be a space before the opening brace. In the single-line form there
164 should be spaces after the opening brace and before the closing brace.
165
166 ```rust
167 Foo { field1, field2: 0 }
168 let f = Foo {
169     field1,
170     field2: an_expr,
171 };
172 ```
173
174 Functional record update syntax is treated like a field, but it must never have
175 a trailing comma. There should be no space after `..`.
176
177 let f = Foo {
178     field1,
179     ..an_expr
180 };
181
182
183 ### Tuple literals
184
185 Use a single-line form where possible. There should not be spaces around the
186 parentheses. Where a single-line form is not possible, each element of the tuple
187 should be on its own block-indented line and there should be a trailing comma.
188
189 ```rust
190 (a, b, c)
191
192 let x = (
193     a_long_expr,
194     another_very_long_expr,
195 );
196 ```
197
198
199 ### Tuple struct literals
200
201 There should be no space between the identifier and the opening parenthesis.
202 Otherwise, follow the rules for tuple literals, e.g., `Foo(a, b)`.
203
204
205 ### Enum literals
206
207 Follow the formatting rules for the various struct literals. Prefer using the
208 name of the enum as a qualifying name, unless the enum is in the prelude. E.g.,
209
210 ```rust
211 Foo::Bar(a, b)
212 Foo::Baz {
213     field1,
214     field2: 1001,
215 }
216 Ok(an_expr)
217 ```
218
219
220 ### Array literals
221
222 For simple array literals, avoid line breaking, no spaces around square
223 brackets, contents of the array should be separated by commas and spaces. If
224 using the repeating initialiser, there should be a space after the semicolon
225 only. Apply the same rules if using the `vec!` or similar macros (always use
226 square brackets here). Examples:
227
228 ```rust
229 fn main() {
230     [1, 2, 3];
231     vec![a, b, c, d];
232     let a = [42; 10];
233 }
234 ```
235
236 If a line must be broken, prefer breaking only after the `;`, if possible.
237 Otherwise, follow the rules below for function calls. In any case, the contents
238 of the initialiser should be block indented and there should be line breaks
239 after the opening bracket and before the closing bracket:
240
241 ```rust
242 fn main() {
243     [
244         a_long_expression();
245         1234567890
246     ]
247     let x = [
248         an_expression,
249         another_expression,
250         a_third_expression,
251     ];
252 }
253 ```
254
255
256 ### Array accesses, indexing, and slicing.
257
258 No spaces around the square brackets, avoid breaking lines if possible, never
259 break a line between the target expression and the opening bracket. If the
260 indexing expression covers multiple lines, then it should be block indented and
261 there should be newlines after the opening brackets and before the closing
262 bracket. However, this should be avoided where possible.
263
264 Examples:
265
266 ```rust
267 fn main() {
268     foo[42];
269     &foo[..10];
270     bar[0..100];
271     foo[4 + 5 / bar];
272     a_long_target[
273         a_long_indexing_expression
274     ];
275 }
276 ```
277
278 ### Unary operations
279
280 Do not include a space between a unary op and its operand (i.e., `!x`, not
281 `! x`). However, there must be a space after `&mut`. Avoid line-breaking
282 between a unary operator and its operand.
283
284 ### Binary operations
285
286 Do include spaces around binary ops (i.e., `x + 1`, not `x+1`) (including `=`
287 and other assignment operators such as `+=` or `*=`).
288
289 For comparison operators, because for `T op U`, `&T op &U` is also implemented:
290 if you have `t: &T`, and `u: U`, prefer `*t op u` to `t op &u`. In general,
291 within expressions, prefer dereferencing to taking references.
292
293 Use parentheses liberally, do not necessarily elide them due to precedence.
294 Tools should not automatically insert or remove parentheses. Do not use spaces
295 to indicate precedence.
296
297 If line-breaking, put the operator on a new line and block indent. Put each
298 sub-expression on its own line. E.g.,
299
300 ```rust
301 foo_bar
302     + bar
303     + baz
304     + qux
305     + whatever
306 ```
307
308 Prefer line-breaking at an assignment operator (either `=` or `+=`, etc.) rather
309 than at other binary operators.
310
311 ### Control flow
312
313 Do not include extraneous parentheses for `if` and `while` expressions.
314
315 ```rust
316 if true {
317 }
318 ```
319
320 is better than
321
322 ```rust
323 if (true) {
324 }
325 ```
326
327 Do include extraneous parentheses if it makes an arithmetic or logic expression
328 easier to understand (`(x * 15) + (y * 20)` is fine)
329
330 ### Function calls
331
332 Do not put a space between the function name, and the opening parenthesis.
333
334 Do not put a space between an argument, and the comma which follows.
335
336 Do put a space between an argument, and the comma which precedes it.
337
338 Prefer not to break a line in the callee expression.
339
340 #### Single-line calls
341
342 Do not put a space between the function name and open paren, between the open
343 paren and the first argument, or between the last argument and the close paren.
344
345 Do not put a comma after the last argument.
346
347 ```rust
348 foo(x, y, z)
349 ```
350
351 #### Multi-line calls
352
353 If the function call is not *small*, it would otherwise over-run the max width,
354 or any argument or the callee is multi-line, then the call should be formatted
355 across multiple lines. In this case, each argument should be on it's own block-
356 indented line, there should be a newline after the opening parenthesis and
357 before the closing parenthesis, and there should be a trailing comma. E.g.,
358
359 ```rust
360 a_function_call(
361     arg1,
362     a_nested_call(a, b),
363 )
364 ```
365
366
367 ### Method calls
368
369 Follow the function rules for calling.
370
371 Do not put any spaces around the `.`.
372
373 ```rust
374 x.foo().bar().baz(x, y, z);
375 ```
376
377
378 ### Macro uses
379
380 Macros which can be parsed like other constructs should be formatted like those
381 constructs. For example, a macro use `foo!(a, b, c)` can be parsed like a
382 function call (ignoring the `!`), therefore it should be formatted following the
383 rules for function calls.
384
385 #### Special case macros
386
387 Macros which take a format string and where all other arguments are *small* may
388 be formatted with arguments before and after the format string on a single line
389 and the format string on its own line, rather than putting each argument on its
390 own line. For example,
391
392 ```rust
393 println!(
394     "Hello {} and {}",
395     name1, name2,
396 );
397
398 assert_eq!(
399     x, y,
400     "x and y were not equal, see {}",
401     reason,
402 );
403 ```
404
405
406 ### Casts (`as`)
407
408 Put spaces before and after `as`:
409
410 ```rust
411 let cstr = "Hi\0" as *const str as *const [u8] as *const std::os::raw::c_char;
412 ```
413
414
415 ### Chains of fields and method calls
416
417 A chain is a sequence of field accesses and/or method calls. A chain may also
418 include the try operator ('?'). E.g., `a.b.c().d` or `foo?.bar().baz?`.
419
420 Prefer formatting on one line if possible, and the chain is *small*. If
421 formatting on multiple lines, each field access or method call in the chain
422 should be on its own line with the line-break before the `.` and after any `?`.
423 Each line should be block-indented. E.g.,
424
425 ```rust
426 let foo = bar
427     .baz?
428     .qux();
429 ```
430
431 If the length of the last line of the first element plus its indentation is
432 less than or equal to the indentation of the second line (and there is space),
433 then combine the first and second lines, e.g.,
434
435 ```rust
436 x.baz?
437     .qux()
438
439 let foo = x
440     .baz?
441     .qux();
442
443 foo(
444     expr1,
445     expr2,
446 ).baz?
447     .qux();
448 ```
449
450 #### Multi-line elements
451
452 If any element in a chain is formatted across multiple lines, then that element
453 and any later elements must be on their own line. Earlier elements may be kept
454 on a single line. E.g.,
455
456 ```rust
457 a.b.c()?.d
458     .foo(
459         an_expr,
460         another_expr,
461     )
462     .bar
463     .baz
464 ```
465
466 Note there is block indent due to the chain and the function call in the above
467 example.
468
469 Prefer formatting the whole chain in multi-line style and each element on one
470 line, rather than putting some elements on multiple lines and some on a single
471 line, e.g.,
472
473 ```rust
474 // Better
475 self.pre_comment
476     .as_ref()
477     .map_or(false, |comment| comment.starts_with("//"))
478
479 // Worse
480 self.pre_comment.as_ref().map_or(
481     false,
482     |comment| comment.starts_with("//"),
483 )
484 ```
485
486 ### Control flow expressions
487
488 This section covers `if`, `if let`, `loop`, `while`, `while let`, and `for`
489 expressions.
490
491 The keyword, any initial clauses, and the opening brace of the block should be
492 on a single line. The usual rules for [block formatting](#blocks) should be
493 applied to the block.
494
495 If there is an `else` component, then the closing brace, `else`, any following
496 clause, and the opening brace should all be on the same line. There should be a
497 single space before and after the `else` keyword. For example:
498
499 ```rust
500 if ... {
501     ...
502 } else {
503     ...
504 }
505
506 if let ... {
507     ...
508 } else if ... {
509     ...
510 } else {
511     ...
512 }
513 ```
514
515 If the control line needs to be broken, then prefer to break before the `=` in
516 `* let` expressions and before `in` in a `for` expression; the following line
517 should be block indented. If the control line is broken for any reason, then the
518 opening brace should be on its own line and not indented. Examples:
519
520 ```rust
521 while let Some(foo)
522     = a_long_expression
523 {
524     ...
525 }
526
527 for foo
528     in a_long_expression
529 {
530     ...
531 }
532
533 if a_long_expression
534     && another_long_expression
535     || a_third_long_expression
536 {
537     ...
538 }
539 ```
540
541 Where the initial clause is multi-lined and ends with one or more closing
542 parentheses, square brackets, or braces, and there is nothing else on that line,
543 and that line is not indented beyond the indent on the first line of the control
544 flow expression, then the opening brace of the block should be put on the same
545 line with a preceding space. For example:
546
547 ```rust
548 if !self.config.file_lines().intersects(
549     &self.codemap.lookup_line_range(
550         stmt.span,
551     ),
552 ) {  // Opening brace on same line as initial clause.
553     ...
554 }
555 ```
556
557
558 #### Single line `if else`
559
560 Formatters may place an `if else` or `if let else` on a single line if it occurs
561 in expression context (i.e., is not a standalone statement), it contains a
562 single `else` clause, and is *small*. For example:
563
564 ```rust
565 let y = if x { 0 } else { 1 };
566
567 // Examples that must be multi-line.
568 let y = if something_very_long {
569     not_small
570 } else {
571     also_not_small
572 };
573
574 if x {
575     0
576 } else {
577     1
578 }
579 ```
580
581
582 ### Match
583
584 Prefer not to line-break inside the discriminant expression. There must always
585 be a line break after the opening brace and before the closing brace. The match
586 arms must be block indented once:
587
588 ```rust
589 match foo {
590     // arms
591 }
592
593 let x = match foo.bar.baz() {
594     // arms
595 };
596 ```
597
598 Use a trailing comma for a match arm if and only if not using a block.
599
600 Never start a match arm pattern with `|`, e.g.,
601
602 ```rust
603 match foo {
604     // Don't do this.
605     | foo => bar,
606     // Or this.
607     | a_very_long_pattern
608     | another_pattern
609     | yet_another_pattern
610     | a_forth_pattern => {
611         ...
612     }
613 }
614 ```
615
616 Prefer
617
618
619 ```rust
620 match foo {
621     foo => bar,
622     a_very_long_pattern
623     | another_pattern
624     | yet_another_pattern
625     | a_forth_pattern => {
626         ...
627     }
628 }
629 ```
630
631 Avoid splitting the left-hand side (before the `=>`) of a match arm where
632 possible. If the right-hand side of the match arm is kept on the same line,
633 never use a block (unless the block is empty).
634
635 If the right-hand side consists of multiple statements or has line comments or
636 the start of the line cannot be fit on the same line as the left-hand side, use
637 a block.
638
639 The body of a block arm should be block indented once.
640
641 Examples:
642
643 ```rust
644 match foo {
645     foo => bar,
646     a_very_long_patten | another_pattern if an_expression() => {
647         no_room_for_this_expression()
648     }
649     foo => {
650         // A comment.
651         an_expression()
652     }
653     foo => {
654         let a = statement();
655         an_expression()
656     }
657     bar => {}
658     // Trailing comma on last item.
659     foo => bar,
660 }
661 ```
662
663 If the body is a single expression with no line comments and not a control flow
664 expression, then it may be started on the same line as the right-hand side. If
665 not, then it must be in a block. Example,
666
667 ```rust
668 match foo {
669     // A combinable expression.
670     foo => a_function_call(another_call(
671         argument1,
672         argument2,
673     )),
674     // A non-combinable expression
675     bar => {
676         a_function_call(
677             another_call(
678                 argument1,
679                 argument2,
680             ),
681             another_argument,
682         )
683     }
684 }
685 ```
686
687 #### Line-breaking
688
689 Where it is possible to use a block form on the right-hand side and avoid
690 breaking the left-hand side, do that. E.g.
691
692 ```rust
693     // Assuming the following line does done fit in the max width
694     a_very_long_pattern | another_pattern => ALongStructName {
695         ...
696     },
697     // Prefer this
698     a_very_long_pattern | another_pattern => {
699         ALongStructName {
700             ...
701         }
702     }
703     // To splitting the pattern.
704 ```
705
706 Never break after `=>` without using the block form of the body.
707
708 If the left-hand side must be split and there is an `if` clause, break before
709 the `if` and block indent. In this case, always use a block body and start the
710 body on a new line:
711
712 ```rust
713     a_very_long_pattern | another_pattern
714         if expr =>
715     {
716         ...
717     }
718 ```
719
720 If required to break the pattern, put each clause of the pattern on its own
721 line with no additional indent, breaking before the `|`. If there is an `if`
722 clause, then you must use the above form:
723
724 ```rust
725     a_very_long_pattern
726     | another_pattern
727     | yet_another_pattern
728     | a_forth_pattern => {
729         ...
730     }
731     a_very_long_pattern
732     | another_pattern
733     | yet_another_pattern
734     | a_forth_pattern
735         if expr =>
736     {
737         ...
738     }
739 ```
740
741 If the pattern is multi-line, and the last line is less wide than the indent, do
742 not put the `if` clause on a newline. E.g.,
743
744 ```rust
745     Token::Dimension {
746          value,
747          ref unit,
748          ..
749     } if num_context.is_ok(context.parsing_mode, value) => {
750         ...
751     }
752 ```
753
754 If every clause in a pattern is *small*, but does not fit on one line, then the
755 pattern may be formatted across multiple lines with as many clauses per line as
756 possible. Again break before a `|`:
757
758 ```rust
759     foo | bar | baz
760     | qux => {
761         ...
762     }
763 ```
764
765 We define a pattern clause to be *small* if it matches the following grammar:
766
767 ```
768 [small, ntp]:
769     - single token
770     - `&[single-line, ntp]`
771
772 [small]:
773     - `[small, ntp]`
774     - unary tuple constructor `([small, ntp])`
775     - `&[small]`
776 ```
777
778 E.g., `&&Some(foo)` matches, `Foo(4, Bar)` does not.
779
780
781 ### Combinable expressions
782
783 Where a function call has a single argument, and that argument is formatted
784 across multiple-lines, the outer call may be formatted as if it were a single-
785 line call. The same combining behaviour may be applied to any similar
786 expressions which have multi-line, block-indented lists of sub-expressions
787 delimited by parentheses (e.g., macros or tuple struct literals). E.g.,
788
789 ```rust
790 foo(bar(
791     an_expr,
792     another_expr,
793 ))
794
795 let x = foo(Bar {
796     field: whatever,
797 });
798
799 foo(|param| {
800     action();
801     foo(param)
802 })
803 ```
804
805 Such behaviour should extend recursively, however, tools may choose to limit the
806 depth of nesting.
807
808 Only where the multi-line sub-expression is a closure with an explicit block,
809 this combining behaviour may be used where there are other arguments, as long as
810 all the arguments and the first line of the closure fit on the first line, the
811 closure is the last argument, and there is only one closure argument:
812
813 ```rust
814 foo(first_arg, x, |param| {
815     action();
816     foo(param)
817 })
818 ```
819
820
821 ### Ranges
822
823 Do not put spaces in ranges, e.g., `0..10`, `x..=y`, `..x.len()`, `foo..`.
824
825 When writing a range with both upper and lower bounds, if the line must be
826 broken, break before the range operator and block indent the second line:
827
828 ```rust
829 a_long_expression
830     ..another_long_expression
831 ```
832
833 For the sake of indicating precedence, we recommend that if either bound is a
834 compound expression, then use parentheses around it, e.g., `..(x + 1)`,
835 `(x.f)..(x.f.len())`, or `0..(x - 10)`.
836
837
838 ### Hexadecimal literals
839
840 Hexadecimal literals may use upper- or lower-case letters, but they must not be
841 mixed within the same literal. Projects should use the same case for all
842 literals, but we do not make a recommendation for either lower- or upper-case.
843 Tools should have an option to convert mixed case literals to upper-case, and
844 may have an option to convert all literals to either lower- or upper-case.
845
846
847 ## Patterns
848
849 Patterns should be formatted like their corresponding expressions. See the
850 section on `match` for additional formatting for patterns in match arms.