Improve the rust style guide doc

- Make the levels of headings consistent in this whole document
- Fix some headings
- Remove redundant empty lines
- Follow the markdown linter advices to use the same symbol for different level of unordered list entries
This commit is contained in:
Lan, Jian 2023-07-31 01:33:33 +08:00
parent 89acdae9f2
commit b4b540ced2
8 changed files with 100 additions and 136 deletions

View File

@ -100,10 +100,12 @@ fn baz() {}
```
### [Module-level items](items.md)
### [Statements](statements.md)
### [Expressions](expressions.md)
### [Types](types.md)
### [Statements](statements.md)
### [Expressions](expressions.md)
### [Types](types.md)
### Comments

View File

@ -2,11 +2,11 @@
[Introduction](README.md)
- [Items](items.md)
- [Statements](statements.md)
- [Expressions](expressions.md)
- [Types and Bounds](types.md)
- [Other style advice](advice.md)
- [`Cargo.toml` conventions](cargo.md)
- [Guiding principles and rationale](principles.md)
- [Nightly-only syntax](nightly.md)
* [Items](items.md)
* [Statements](statements.md)
* [Expressions](expressions.md)
* [Types and Bounds](types.md)
* [Other style advice](advice.md)
* [`Cargo.toml` conventions](cargo.md)
* [Guiding principles and rationale](principles.md)
* [Nightly-only syntax](nightly.md)

View File

@ -18,16 +18,16 @@ if y {
## Names
* Types shall be `UpperCamelCase`,
* Enum variants shall be `UpperCamelCase`,
* Struct fields shall be `snake_case`,
* Function and method names shall be `snake_case`,
* Local variables shall be `snake_case`,
* Macro names shall be `snake_case`,
* Constants (`const`s and immutable `static`s) shall be `SCREAMING_SNAKE_CASE`.
* When a name is forbidden because it is a reserved word (such as `crate`),
either use a raw identifier (`r#crate`) or use a trailing underscore
(`crate_`). Don't misspell the word (`krate`).
* Types shall be `UpperCamelCase`,
* Enum variants shall be `UpperCamelCase`,
* Struct fields shall be `snake_case`,
* Function and method names shall be `snake_case`,
* Local variables shall be `snake_case`,
* Macro names shall be `snake_case`,
* Constants (`const`s and immutable `static`s) shall be `SCREAMING_SNAKE_CASE`.
* When a name is forbidden because it is a reserved word (such as `crate`),
either use a raw identifier (`r#crate`) or use a trailing underscore
(`crate_`). Don't misspell the word (`krate`).
### Modules

View File

@ -1,6 +1,6 @@
## Expressions
# Expressions
### Blocks
## Blocks
A block expression must have a newline after the initial `{` and before the
terminal `}`, unless it qualifies to be written as a single line based on
@ -116,8 +116,7 @@ fn main() {
}
```
### Closures
## Closures
Don't put any extra spaces before the first `|` (unless the closure is prefixed
by a keyword such as `move`); put a space between the second `|` and the
@ -155,8 +154,7 @@ move |arg1: i32, arg2: i32| -> i32 {
}
```
### Struct literals
## Struct literals
If a struct literal is *small*, format it on a single line, and do not use a
trailing comma. If not, split it across multiple lines, with each field on its
@ -185,8 +183,7 @@ let f = Foo {
};
```
### Tuple literals
## Tuple literals
Use a single-line form where possible. Do not put spaces between the opening
parenthesis and the first element, or between the last element and the closing
@ -205,8 +202,7 @@ let x = (
);
```
### Tuple struct literals
## Tuple struct literals
Do not put space between the identifier and the opening parenthesis. Otherwise,
follow the rules for tuple literals:
@ -220,8 +216,7 @@ let x = Foo(
);
```
### Enum literals
## Enum literals
Follow the formatting rules for the various struct literals. Prefer using the
name of the enum as a qualifying name, unless the enum is in the prelude:
@ -235,8 +230,7 @@ Foo::Baz {
Ok(an_expr)
```
### Array literals
## Array literals
Write small array literals on a single line. Do not put spaces between the opening
square bracket and the first element, or between the last element and the closing
@ -276,8 +270,7 @@ fn main() {
}
```
### Array accesses, indexing, and slicing.
## Array accesses, indexing, and slicing
Don't put spaces around the square brackets. Avoid breaking lines if possible.
Never break a line between the target expression and the opening square
@ -300,13 +293,13 @@ fn main() {
}
```
### Unary operations
## Unary operations
Do not include a space between a unary op and its operand (i.e., `!x`, not
`! x`). However, there must be a space after `&mut`. Avoid line-breaking
between a unary operator and its operand.
### Binary operations
## Binary operations
Do include spaces around binary ops (i.e., `x + 1`, not `x+1`) (including `=`
and other assignment operators such as `+=` or `*=`).
@ -335,7 +328,7 @@ foo_bar
Prefer line-breaking at an assignment operator (either `=` or `+=`, etc.) rather
than at other binary operators.
### Control flow
## Control flow
Do not include extraneous parentheses for `if` and `while` expressions.
@ -354,7 +347,7 @@ if (true) {
Do include extraneous parentheses if it makes an arithmetic or logic expression
easier to understand (`(x * 15) + (y * 20)` is fine)
### Function calls
## Function calls
Do not put a space between the function name, and the opening parenthesis.
@ -364,7 +357,7 @@ Do put a space between an argument, and the comma which precedes it.
Prefer not to break a line in the callee expression.
#### Single-line calls
### Single-line calls
Do not put a space between the function name and open paren, between the open
paren and the first argument, or between the last argument and the close paren.
@ -375,7 +368,7 @@ Do not put a comma after the last argument.
foo(x, y, z)
```
#### Multi-line calls
### Multi-line calls
If the function call is not *small*, it would otherwise over-run the max width,
or any argument or the callee is multi-line, then format the call across
@ -390,8 +383,7 @@ a_function_call(
)
```
### Method calls
## Method calls
Follow the function rules for calling.
@ -401,15 +393,14 @@ Do not put any spaces around the `.`.
x.foo().bar().baz(x, y, z);
```
### Macro uses
## Macro uses
If a macro can be parsed like other constructs, format it like those
constructs. For example, a macro use `foo!(a, b, c)` can be parsed like a
function call (ignoring the `!`), so format it using the rules for function
calls.
#### Special case macros
### Special case macros
For macros which take a format string, if all other arguments are *small*,
format the arguments before the format string on a single line if they fit, and
@ -430,8 +421,7 @@ assert_eq!(
);
```
### Casts (`as`)
## Casts (`as`)
Put spaces before and after `as`:
@ -439,8 +429,7 @@ Put spaces before and after `as`:
let cstr = "Hi\0" as *const str as *const [u8] as *const std::os::raw::c_char;
```
### Chains of fields and method calls
## Chains of fields and method calls
A chain is a sequence of field accesses, method calls, and/or uses of the try
operator `?`. E.g., `a.b.c().d` or `foo?.bar().baz?`.
@ -478,7 +467,7 @@ foo(
.qux();
```
#### Multi-line elements
### Multi-line elements
If any element in a chain is formatted across multiple lines, put that element
and any later elements on their own lines.
@ -513,7 +502,7 @@ self.pre_comment.as_ref().map_or(
)
```
### Control flow expressions
## Control flow expressions
This section covers `if`, `if let`, `loop`, `while`, `while let`, and `for`
expressions.
@ -584,8 +573,7 @@ if !self.config.file_lines().intersects(
}
```
#### Single line `if else`
### Single line `if else`
Put an `if else` or `if let else` on a single line if it occurs in expression
context (i.e., is not a standalone statement), it contains a single `else`
@ -608,8 +596,7 @@ if x {
}
```
### Match
## Match
Prefer not to line-break inside the discriminant expression. Always break after
the opening brace and before the closing brace. Block-indent the match arms
@ -718,7 +705,7 @@ match foo {
}
```
#### Line-breaking
### Line-breaking
If using a block form on the right-hand side of a match arm makes it possible
to avoid breaking on the left-hand side, do that:
@ -812,8 +799,7 @@ small_no_tuple:
E.g., `&&Some(foo)` matches, `Foo(4, Bar)` does not.
### Combinable expressions
## Combinable expressions
Where a function call has a single argument, and that argument is formatted
across multiple-lines, format the outer call as if it were a single-line call,
@ -861,8 +847,7 @@ foo(first_arg, x, |param| {
})
```
### Ranges
## Ranges
Do not put spaces in ranges, e.g., `0..10`, `x..=y`, `..x.len()`, `foo..`.
@ -879,8 +864,7 @@ For the sake of indicating precedence, if either bound is a compound
expression, use parentheses around it, e.g., `..(x + 1)`, `(x.f)..(x.f.len())`,
or `0..(x - 10)`.
### Hexadecimal literals
## Hexadecimal literals
Hexadecimal literals may use upper- or lower-case letters, but they must not be
mixed within the same literal. Projects should use the same case for all

View File

@ -1,4 +1,4 @@
## Items
# Items
Items consist of the set of things permitted at the top level of a module.
However, Rust also allows some items to appear within some other types of
@ -16,7 +16,7 @@ names.
Don't automatically move module declarations annotated with `#[macro_use]`,
since that might change semantics.
### Function definitions
## Function definitions
In Rust, people often find functions by searching for `fn [function-name]`, so
the formatting of function definitions must enable this.
@ -46,14 +46,13 @@ fn foo(
Note the trailing comma on the last argument.
### Tuples and tuple structs
## Tuples and tuple structs
Write the type list as you would a parameter list to a function.
Build a tuple or tuple struct as you would call a function.
#### Single-line
### Single-line
```rust
struct Bar(Type1, Type2);
@ -62,7 +61,7 @@ let x = Bar(11, 22);
let y = (11, 22, 33);
```
### Enums
## Enums
In the declaration, put each variant on its own line, block indented.
@ -96,8 +95,7 @@ multiple lines, use the multi-line formatting for all struct variants. However,
such a situation might be an indication that you should factor out the fields
of the variant into their own struct.
### Structs and Unions
## Structs and Unions
Struct names follow on the same line as the `struct` keyword, with the opening
brace on the same line when it fits within the right margin. All struct fields
@ -138,8 +136,7 @@ union Foo {
}
```
### Tuple structs
## Tuple structs
Put the whole struct on one line if possible. Separate types within the
parentheses using a comma and space. Don't use a trailing comma for a
@ -165,8 +162,7 @@ pub struct Foo(
);
```
### Traits
## Traits
Use block-indent for trait items. If there are no items, format the trait (including its `{}`)
on a single line. Otherwise, break after the opening brace and before
@ -204,8 +200,7 @@ pub trait IndexRanges:
}
```
### Impls
## Impls
Use block-indent for impl items. If there are no items, format the impl
(including its `{}`) on a single line. Otherwise, break after the opening brace
@ -231,15 +226,13 @@ impl Bar
}
```
### Extern crate
## Extern crate
`extern crate foo;`
Use spaces around keywords, no spaces around the semicolon.
### Modules
## Modules
```rust
mod foo {
@ -253,7 +246,7 @@ mod foo;
Use spaces around keywords and before the opening brace, no spaces around the
semicolon.
### macro\_rules!
## `macro_rules!`
Use `{}` for the full definition of the macro.
@ -262,8 +255,7 @@ macro_rules! foo {
}
```
### Generics
## Generics
Prefer to put a generics clause on one line. Break other parts of an item
declaration rather than line-breaking a generics clause. If a generics clause is
@ -299,8 +291,7 @@ If an associated type is bound in a generic type, put spaces around the `=`:
Prefer to use single-letter names for generic parameters.
### `where` clauses
## `where` clauses
These rules apply for `where` clauses on any item.
@ -373,7 +364,7 @@ where
+ Index<RangeFull>,
```
### Type aliases
## Type aliases
Keep type aliases on one line when they fit. If necessary to break the line, do
so after the `=`, and block-indent the right-hand side:
@ -398,8 +389,7 @@ where
= AnEvenLongerType<T, U, Foo<T>>;
```
### Associated types
## Associated types
Format associated types like type aliases. Where an associated type has a
bound, put a space after the colon but not before:
@ -408,15 +398,13 @@ bound, put a space after the colon but not before:
pub type Foo: Bar;
```
### extern items
## extern items
When writing extern items (such as `extern "C" fn`), always specify the ABI.
For example, write `extern "C" fn foo ...`, not `extern fn foo ...`, or
`extern "C" { ... }`.
### Imports (`use` statements)
## Imports (`use` statements)
Format imports on one line where possible. Don't put spaces around braces.
@ -426,8 +414,7 @@ use a::b::d::*;
use a::b::{foo, bar, baz};
```
#### Large list imports
### Large list imports
Prefer to use multiple imports rather than a multi-line import. However, tools
should not split imports by default.
@ -437,7 +424,6 @@ does not fit within the max width, or because of the rules for nested imports
below), then break after the opening brace and before the closing brace, use a
trailing comma, and block indent the names.
```rust
// Prefer
foo::{long, list, of, imports};
@ -450,8 +436,7 @@ foo::{
};
```
#### Ordering of imports
### Ordering of imports
A *group* of imports is a set of imports on the same or sequential lines. One or
more blank lines or other items (e.g., a function) separate groups of imports.
@ -459,7 +444,6 @@ more blank lines or other items (e.g., a function) separate groups of imports.
Within a group of imports, imports must be sorted ASCIIbetically (uppercase
before lowercase). Groups of imports must not be merged or re-ordered.
E.g., input:
```rust
@ -483,15 +467,14 @@ use b;
Because of `macro_use`, attributes must also start a new group and prevent
re-ordering.
#### Ordering list import
### Ordering list import
Names in a list import must be sorted ASCIIbetically, but with `self` and
`super` first, and groups and glob imports last. This applies recursively. For
example, `a::*` comes before `b::a` but `a::b` comes before `a::*`. E.g.,
`use foo::bar::{a, b::c, b::d, b::d::{x, y, z}, b::{self, r, s}};`.
#### Normalisation
### Normalisation
Tools must make the following normalisations, recursively:
@ -502,8 +485,7 @@ Tools must make the following normalisations, recursively:
Tools must not otherwise merge or un-merge import lists or adjust glob imports
(without an explicit option).
#### Nested imports
### Nested imports
If there are any nested imports in a list import, then use the multi-line form,
even if the import fits on one line. Each nested import must be on its own line,
@ -519,8 +501,7 @@ use a::b::{
};
```
#### Merging/un-merging imports
### Merging/un-merging imports
An example:

View File

@ -4,26 +4,26 @@ When deciding on style guidelines, the style team follows these guiding
principles (in rough priority order):
* readability
- scan-ability
- avoiding misleading formatting
- accessibility - readable and editable by users using the widest
variety of hardware, including non-visual accessibility interfaces
- readability of code in contexts without syntax highlighting or IDE
assistance, such as rustc error messages, diffs, grep, and other
plain-text contexts
* scan-ability
* avoiding misleading formatting
* accessibility - readable and editable by users using the widest
variety of hardware, including non-visual accessibility interfaces
* readability of code in contexts without syntax highlighting or IDE
assistance, such as rustc error messages, diffs, grep, and other
plain-text contexts
* aesthetics
- sense of 'beauty'
- consistent with other languages/tools
* sense of 'beauty'
* consistent with other languages/tools
* specifics
- compatibility with version control practices - preserving diffs,
merge-friendliness, etc.
- preventing rightward drift
- minimising vertical space
* compatibility with version control practices - preserving diffs,
merge-friendliness, etc.
* preventing rightward drift
* minimising vertical space
* application
- ease of manual application
- ease of implementation (in `rustfmt`, and in other tools/editors/code generators)
- internal consistency
- simplicity of formatting rules
* ease of manual application
* ease of implementation (in `rustfmt`, and in other tools/editors/code generators)
* internal consistency
* simplicity of formatting rules

View File

@ -1,6 +1,6 @@
## Statements
# Statements
### Let statements
## Let statements
Put a space after the `:` and on both sides of the `=` (if they are present).
Don't put a space before the semicolon.
@ -28,7 +28,6 @@ use block indentation. If the type requires multiple lines, even after
line-breaking after the `:`, then place the first line on the same line as the
`:`, subject to the [combining rules](expressions.html#combinable-expressions).
```rust
let pattern:
Type =
@ -101,7 +100,7 @@ let Foo {
);
```
#### else blocks (let-else statements)
### else blocks (let-else statements)
A let statement can contain an `else` component, making it a let-else statement.
In this case, always apply the same formatting rules to the components preceding
@ -231,7 +230,7 @@ fn main() {
}
```
### Macros in statement position
## Macros in statement position
For a macro use in statement position, use parentheses or square brackets as
delimiters, and terminate it with a semicolon. Do not put spaces around the
@ -242,8 +241,7 @@ name, `!`, the delimiters, or the `;`.
a_macro!(...);
```
### Expressions in statement position
## Expressions in statement position
Do not put space between the expression and the semicolon.

View File

@ -1,6 +1,6 @@
## Types and Bounds
# Types and Bounds
### Single line formatting
## Single line formatting
* `[T]` no spaces
* `[T; expr]`, e.g., `[u32; 42]`, `[Vec<Foo>; 10 * 2 + foo()]` (space after colon, no spaces around square brackets)
@ -16,8 +16,7 @@
Do not put space around parentheses used in types, e.g., `(Foo)`
### Line breaks
## Line breaks
Avoid breaking lines in types where possible. Prefer breaking at outermost scope, e.g., prefer