Skip to content

Commit 42fa7df

Browse files
committed
style-guide: Expand documentation on as casts (mostly like a binary operator)
`as` casts currently get formatted like a binary operator, except that the second line can stack several `as` casts rather than breaking them each onto their own line. Merge `as` into a subsection of the binary operators section, and then go into detail on the one difference between `as` formatting and binary operator formatting.
1 parent 736ef39 commit 42fa7df

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/doc/style-guide/src/expressions.md

+20-8
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,26 @@ foo_bar
328328
Prefer line-breaking at an assignment operator (either `=` or `+=`, etc.) rather
329329
than at other binary operators.
330330

331+
### Casts (`as`)
332+
333+
Format `as` casts like a binary operator. In particular, always include spaces
334+
around `as`, and if line-breaking, break before the `as` (never after) and
335+
block-indent the subsequent line. Format the type on the right-hand side using
336+
the rules for types.
337+
338+
However, unlike with other binary operators, if chaining a series of `as` casts
339+
that require line-breaking, and line-breaking before the first `as` suffices to
340+
make the remainder fit on the next line, don't break before any subsequent
341+
`as`; instead, leave the series of types all on the same line:
342+
343+
```rust
344+
let cstr = very_long_expression()
345+
as *const str as *const [u8] as *const std::os::raw::c_char;
346+
```
347+
348+
If the subsequent line still requires line-breaking, break and block-indent
349+
before each `as` as with other binary operators.
350+
331351
## Control flow
332352

333353
Do not include extraneous parentheses for `if` and `while` expressions.
@@ -421,14 +441,6 @@ assert_eq!(
421441
);
422442
```
423443

424-
## Casts (`as`)
425-
426-
Put spaces before and after `as`:
427-
428-
```rust
429-
let cstr = "Hi\0" as *const str as *const [u8] as *const std::os::raw::c_char;
430-
```
431-
432444
## Chains of fields and method calls
433445

434446
A chain is a sequence of field accesses, method calls, and/or uses of the try

0 commit comments

Comments
 (0)