Skip to content

Commit 47277ab

Browse files
authored
Rollup merge of #114394 - joshtriplett:style-guide-as, r=calebcartwright
style-guide: Document formatting of `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. Document this. As far as I can tell (cc `@calebcartwright` for verification), this is not a 2024 edition change, it just documents current behavior.
2 parents ad36b5a + 42fa7df commit 47277ab

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

Diff for: 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.
@@ -426,14 +446,6 @@ assert_eq!(
426446
);
427447
```
428448

429-
## Casts (`as`)
430-
431-
Put spaces before and after `as`:
432-
433-
```rust
434-
let cstr = "Hi\0" as *const str as *const [u8] as *const std::os::raw::c_char;
435-
```
436-
437449
## Chains of fields and method calls
438450

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

0 commit comments

Comments
 (0)