diff --git a/README.md b/README.md index d20f038..e2d5ee7 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,9 @@ > - 首次于 2023-07-31 翻译完全部内容,欢迎纠正——最后更新时间 2023-07-31。 > - 期待更多朋友加入 [Rust 中文翻译项目组](https://github.com/rust-lang-cn),协助我们,一起更新完善中文版,感激不尽! -这是《Rust 语言风格指南》中文版,翻译自 [Rust 源码中的《style-guide Book》][style-guide-src]。 +这是《Rust 语言风格指南》中文版,翻译自 [Rust 源码中的《The Rust Style Guide》][style-guide-src]。 -在线版可在本组织官网上阅读,包括[全球站点][style-guide-cn]或[国内站点][style-guide-cn-zh](**支持同一页面中英双语切换**),或者在 Rust 官网上[阅读英文版][style-guide-en]。 +在线版可在本组织官网上阅读,包括[全球站点][style-guide-cn]或[国内站点][style-guide-cn-zh](**均支持同一页面中英双语切换**),或者在 Rust 官网上[阅读英文版][style-guide-en]。 [style-guide-src]: https://github.com/rust-lang/rust/tree/master/src/doc/style-guide [style-guide-cn]: https://rustwiki.org/zh-CN/style-guide/ diff --git a/src/README.md b/src/README.md index c98ae15..9ba057a 100644 --- a/src/README.md +++ b/src/README.md @@ -28,7 +28,7 @@ 与视觉化缩进(visual indent)相比,更倾向于分块缩进: -```rust +```rust,ignore // 块缩进 a_function_call( foo, @@ -42,12 +42,11 @@ a_function_call(foo, 这样做的差异就会变小(例如,在上例中重命名了`a_function_call`),向右移动的情况也会减少。 -### Trailing commas +### 尾逗号 -In comma-separated lists of any kind, use a trailing comma when followed by a -newline: +在任何类型的逗号分隔列表中,如果后面有换行符,请使用尾逗号: -```rust +```rust,ignore function_call( argument, another_argument, @@ -60,16 +59,13 @@ let array = [ ]; ``` -This makes moving code (e.g., by copy and paste) easier, and makes diffs -smaller, as appending or removing items does not require modifying another line -to add or remove a comma. +这使得移动代码(例如通过复制和粘贴)变得更容易,并使差异更小,因为添加或删除项目不需要修改另一行来添加或删除逗号。 -### Blank lines +### 空行 -Separate items and statements by either zero or one blank lines (i.e., one or -two newlines). E.g, +不用空行或一个空行(即 1 或 2 个换行符)分隔程序项和语句。例如: -```rust +```rust,ignore fn foo() { let x = ...; @@ -81,54 +77,43 @@ fn bar() {} fn baz() {} ``` -### [Module-level items](items.md) -### [Statements](statements.md) -### [Expressions](expressions.md) -### [Types](types.md) +### [模块级别的程序序项](items.md) +### [语句](statements.md) +### [表达式](expressions.md) +### [类型](types.md) +### 注释 -### Comments +以下关于注释的指导原则仅为建议,机器格式化工具可能会跳过注释格式化。 -The following guidelines for comments are recommendations only, a mechanical -formatter might skip formatting of comments. +行注释 (`//`) 优先于块注释 (`/* ... */`)。 -Prefer line comments (`//`) to block comments (`/* ... */`). +使用行注释时,在开头符号后留一个空格。 -When using line comments, put a single space after the opening sigil. +使用单行块注释时,在开头符号后和结尾符号前各留一个空格。对于多行块注释,在开头符号后加一个换行符,在结尾符号前加一个换行符。 -When using single-line block comments, put a single space after the opening -sigil and before the closing sigil. For multi-line block comments, put a -newline after the opening sigil, and a newline before the closing sigil. +注释最好独立成行。如果注释紧跟代码,则在注释前空格一个。如果块注释出现在行内,则使用周围的空格,就像使用标识符或关键字一样。不要在注释后或多行注释中任何一行的末尾使用拖尾空格。例如: -Prefer to put a comment on its own line. Where a comment follows code, put a -single space before it. Where a block comment appears inline, use surrounding -whitespace as if it were an identifier or keyword. Do not include trailing -whitespace after a comment or at the end of any line in a multi-line comment. -Examples: - -```rust -// A comment on an item. +```rust,ignore +// 程序项中的注释。 struct Foo { ... } -fn foo() {} // A comment after an item. +fn foo() {} // 在一个项后的注释。 -pub fn foo(/* a comment before an argument */ x: T) {...} +pub fn foo(/* 在参数前的注释 */ x: T) {...} ``` -Comments should usually be complete sentences. Start with a capital letter, end -with a period (`.`). An inline block comment may be treated as a note without -punctuation. +注释通常应是完整的句子。英文的注释开头用大写字母,结尾用句点(`.`)(译注:若是使用中文注释,则换成中文标点符号)。内联块注释可视为不带标点符号的注释。 -Source lines which are entirely a comment should be limited to 80 characters -in length (including comment sigils, but excluding indentation) or the maximum -width of the line (including comment sigils and indentation), whichever is -smaller: +完全是注释的源文件行长度应限制在 80 个字符以内(包括注释符号,但不包括缩进),或该行的最大宽度(包括注释符号和缩进),以较小者为准: -```rust +```rust,ignore // This comment goes up to the ................................. 80 char margin. +// 该注释的边距为 ............................. 80 字符。 { // This comment is .............................................. 80 chars wide. + // 此注释宽 ............................................................. 80 字符。 } { @@ -138,6 +123,7 @@ smaller: { { // This comment is limited by the ......................... 100 char margin. + // 此注释受 ................................................ 100 字符边距的限制。 } } } @@ -146,24 +132,21 @@ smaller: } ``` -#### Doc comments +#### 文档注释 -Prefer line comments (`///`) to block comments (`/** ... */`). +优先使用行注释 (`///`) 而不是块注释 (`/** ... */`)。 -Prefer outer doc comments (`///` or `/** ... */`), only use inner doc comments -(`//!` and `/*! ... */`) to write module-level or crate-level documentation. +优先使用外层文档注释(`///` 或 `/** ... */`),仅使用内层文档注释(`//!` 和 `/*! ... */`)编写模块级或 crate 块级的文档。 -Put doc comments before attributes. +将文档注释放在属性之前。 -### Attributes +### 属性 -Put each attribute on its own line, indented to the level of the item. -In the case of inner attributes (`#!`), indent it to the level of the inside of -the item. Prefer outer attributes, where possible. +每个属性放在单独一行,跟程序项保持一致的缩进。如果是内部属性 (`#!`),则缩进到程序项内部的位置。尽可能使用外属性。 -For attributes with argument lists, format like functions. +对于带有参数列表的属性,格式应与函数类似。 -```rust +```rust,ignore #[repr(C)] #[foo(foo, bar)] #[long_multi_line_attribute( @@ -178,43 +161,34 @@ struct CRepr { } ``` +对于带有等号的属性,在 `=` 前后各加一个空格,如 `#[foo = 42]`。 + +必须只有一个 `derive` 属性。工具的作者们要注意:如果将多个 `derive` 属性合并为一个属性,通常必须保留派生名称的顺序,以保证正确性: `#[derive(Foo)] #[derive(Bar)] struct Baz;` 必须格式化为 `#[derive(Foo, Bar)] struct Baz;`。 + For attributes with an equal sign, put a single space before and after the `=`, e.g., `#[foo = 42]`. -There must only be a single `derive` attribute. Note for tool authors: if -combining multiple `derive` attributes into a single attribute, the ordering of -the derived names must generally be preserved for correctness: -`#[derive(Foo)] #[derive(Bar)] struct Baz;` must be formatted to -`#[derive(Foo, Bar)] struct Baz;`. - -### *small* items +### **简短**程序项 -In many places in this guide we specify formatting that depends on a code -construct being *small*. For example, single-line vs multi-line struct -literals: +在本指南的许多地方,我们指定的格式取决于代码结构的**简短**。例如,单行结构文字与多行结构文字: -```rust -// Normal formatting +```rust,ignore +// 正常格式化 Foo { f1: an_expression, f2: another_expression(), } -// "small" formatting +// “简短”格式化 Foo { f1, f2 } ``` -We leave it to individual tools to decide on exactly what *small* means. In -particular, tools are free to use different definitions in different -circumstances. +我们让各个工具自行决定“简短”的确切含义。特别是,在不同的情况下,工具可以自由使用不同的定义。 -Some suitable heuristics are the size of the item (in characters) or the -complexity of an item (for example, that all components must be simple names, -not more complex sub-expressions). For more discussion on suitable heuristics, -see [this issue](https://github.com/rust-lang-nursery/fmt-rfcs/issues/47). +一些合适的启发式方法是程序项的大小(以字符为单位)或程序项的复杂程度(例如,所有组件必须是简单的名称,而不是更复杂的子表达式)。有关合适的启发式方法的更多讨论,请参考[此讨论问题](https://github.com/rust-lang-nursery/fmt-rfcs/issues/47)。 -## [Non-formatting conventions](advice.md) +## [非格式化约定](advice.md) -## [Cargo.toml conventions](cargo.md) +## [Cargo.toml 的约定](cargo.md) -## [Principles used for deciding these guidelines](principles.md) +## [决定这些准则的原则](principles.md) diff --git a/src/advice.md b/src/advice.md index 25e42b7..6d7704f 100644 --- a/src/advice.md +++ b/src/advice.md @@ -4,7 +4,7 @@ 尽可能使用 Rust 面向表达式的特性; -```rust +```rust,ignore // 使用 let x = if y { 1 } else { 0 }; // 不使用 diff --git a/src/cargo.md b/src/cargo.md index 9ff0c12..b74cc0b 100644 --- a/src/cargo.md +++ b/src/cargo.md @@ -18,7 +18,7 @@ 对于数组值(如特征列表),如果合适,可将整个列表与键放在同一行。否则,使用分块缩进:在开头的方括号后加一个换行符,每个项目缩进一级,每个项目(包括最后一个项目)后加一个逗号,最后一个项目后将结尾的方括号放在一行的开头。 -```rust +```rust,ignore some_feature = [ "another_feature", "yet_another_feature", diff --git a/src/expressions.md b/src/expressions.md index 5f6a279..d11f54c 100644 --- a/src/expressions.md +++ b/src/expressions.md @@ -6,7 +6,7 @@ 代码块前的关键字(如 `unsafe` 或 `async`)必须与开头的括号在同一行,关键字与开头的括号之间用一个空格隔开。缩进代码块的内容。 -```rust +```rust,ignore fn block_as_stmt() { a_call(); @@ -41,7 +41,7 @@ fn unsafe_block_as_stmt() { If a block has an attribute, put it on its own line before the block: -```rust +```rust,ignore fn block_as_stmt() { #[an_attribute] { @@ -69,7 +69,7 @@ closing brace. Examples: -```rust +```rust,ignore fn main() { // Single line let _ = { a_call() }; @@ -125,7 +125,7 @@ a return type, when there are statements, when there are comments inside the closure, or when the body expression is a control-flow expression that spans multiple lines. If using braces, follow the rules above for blocks. Examples: -```rust +```rust,ignore |arg1, arg2| expr move |arg1: i32, arg2: i32| -> i32 { @@ -163,7 +163,7 @@ For each `field: value` entry, put a space after the colon only. Put a space before the opening brace. In the single-line form, put spaces after the opening brace and before the closing brace. -```rust +```rust,ignore Foo { field1, field2: 0 } let f = Foo { field1, @@ -174,7 +174,7 @@ let f = Foo { Functional record update syntax is treated like a field, but it must never have a trailing comma. Do not put a space after `..`. -```rust +```rust,ignore let f = Foo { field1, ..an_expr @@ -192,7 +192,7 @@ Where a single-line form is not possible, write the tuple across multiple lines, with each element of the tuple on its own block-indented line, and use a trailing comma. -```rust +```rust,ignore (a, b, c) let x = ( @@ -207,7 +207,7 @@ let x = ( Do not put space between the identifier and the opening parenthesis. Otherwise, follow the rules for tuple literals: -```rust +```rust,ignore Foo(a, b, c) let x = Foo( @@ -222,7 +222,7 @@ let x = Foo( 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: -```rust +```rust,ignore Foo::Bar(a, b) Foo::Baz { field1, @@ -244,7 +244,7 @@ only. Apply the same rules if using `vec!` or similar array-like macros; always use square brackets with such macros. Examples: -```rust +```rust,ignore fn main() { let x = [1, 2, 3]; let y = vec![a, b, c, d]; @@ -258,7 +258,7 @@ for function calls. In any case, block-indent the contents of the initializer, and put line breaks after the opening square bracket and before the closing square bracket: -```rust +```rust,ignore fn main() { [ a_long_expression(); @@ -284,7 +284,7 @@ bracket: Examples: -```rust +```rust,ignore fn main() { foo[42]; &foo[..10]; @@ -320,7 +320,7 @@ If line-breaking, block-indent each subsequent line. For assignment operators, break after the operator; for all other operators, put the operator on the subsequent line. Put each sub-expression on its own line: -```rust +```rust,ignore foo_bar + bar + baz @@ -335,14 +335,14 @@ than at other binary operators. Do not include extraneous parentheses for `if` and `while` expressions. -```rust +```rust,ignore if true { } ``` is better than -```rust +```rust,ignore if (true) { } ``` @@ -367,7 +367,7 @@ paren and the first argument, or between the last argument and the close paren. Do not put a comma after the last argument. -```rust +```rust,ignore foo(x, y, z) ``` @@ -379,7 +379,7 @@ multiple lines. In this case, put each argument on its own block-indented line, break after the opening parenthesis and before the closing parenthesis, and use a trailing comma: -```rust +```rust,ignore a_function_call( arg1, a_nested_call(a, b), @@ -393,7 +393,7 @@ Follow the function rules for calling. Do not put any spaces around the `.`. -```rust +```rust,ignore x.foo().bar().baz(x, y, z); ``` @@ -413,7 +413,7 @@ format the arguments after the format string on a single line if they fit, with the format string on its own line. If the arguments are not small or do not fit, put each on its own line as with a function. For example: -```rust +```rust,ignore println!( "Hello {} and {}", name1, name2, @@ -431,7 +431,7 @@ assert_eq!( Put spaces before and after `as`: -```rust +```rust,ignore let cstr = "Hi\0" as *const str as *const [u8] as *const std::os::raw::c_char; ``` @@ -446,7 +446,7 @@ If formatting on multiple lines, put each field access or method call in the chain on its own line, with the line-break before the `.` and after any `?`. Block-indent each subsequent line: -```rust +```rust,ignore let foo = bar .baz? .qux(); @@ -456,7 +456,7 @@ If the length of the last line of the first element plus its indentation is less than or equal to the indentation of the second line, then combine the first and second lines if they fit. Apply this rule recursively. -```rust +```rust,ignore x.baz? .qux() @@ -479,7 +479,7 @@ foo( If any element in a chain is formatted across multiple lines, put that element and any later elements on their own lines. -```rust +```rust,ignore a.b.c()? .foo( an_expr, @@ -496,7 +496,7 @@ Prefer formatting the whole chain in multi-line style and each element on one line, rather than putting some elements on multiple lines and some on a single line, e.g., -```rust +```rust,ignore // Better self.pre_comment .as_ref() @@ -522,7 +522,7 @@ If there is an `else` component, then put the closing brace, `else`, any following clause, and the opening brace all on the same line, with a single space before and after the `else` keyword: -```rust +```rust,ignore if ... { ... } else { @@ -543,7 +543,7 @@ let` expressions and before `in` in a `for` expression; block-indent the following line. If the control line is broken for any reason, put the opening brace on its own line, not indented. Examples: -```rust +```rust,ignore while let Some(foo) = a_long_expression { @@ -570,7 +570,7 @@ line, and that line is not indented beyond the indent on the first line of the control flow expression, then put the opening brace of the block on the same line with a preceding space. For example: -```rust +```rust,ignore if !self.config.file_lines().intersects( &self.codemap.lookup_line_range( stmt.span, @@ -587,7 +587,7 @@ 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` clause, and is *small*: -```rust +```rust,ignore let y = if x { 0 } else { 1 }; // Examples that must be multi-line. @@ -611,7 +611,7 @@ 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 once: -```rust +```rust,ignore match foo { // arms } @@ -625,7 +625,7 @@ Use a trailing comma for a match arm if and only if not using a block. Never start a match arm pattern with `|`: -```rust +```rust,ignore match foo { // Don't do this. | foo => bar, @@ -641,7 +641,7 @@ match foo { Prefer: -```rust +```rust,ignore match foo { foo => bar, a_very_long_pattern @@ -666,7 +666,7 @@ Block-indent the body of a block arm. Examples: -```rust +```rust,ignore match foo { foo => bar, a_very_long_pattern | another_pattern if an_expression() => { @@ -694,7 +694,7 @@ If the body is a single expression with no line comments and not a control flow expression, start it on the same line as the left-hand side. If not, then it must be in a block. Example: -```rust +```rust,ignore match foo { // A combinable expression. foo => a_function_call(another_call( @@ -719,7 +719,7 @@ match foo { 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: -```rust +```rust,ignore // Assuming the following line does not fit in the max width a_very_long_pattern | another_pattern => ALongStructName { ... @@ -739,7 +739,7 @@ If the left-hand side must be split and there is an `if` clause, break before the `if` and block indent. In this case, always use a block body and start the body on a new line: -```rust +```rust,ignore a_very_long_pattern | another_pattern if expr => { @@ -751,7 +751,7 @@ If required to break the pattern, put each clause of the pattern on its own line with no additional indent, breaking before the `|`. If there is an `if` clause, use the above form: -```rust +```rust,ignore a_very_long_pattern | another_pattern | yet_another_pattern @@ -771,7 +771,7 @@ clause, use the above form: If the pattern is multi-line, and the last line is less wide than the indent, do not put the `if` clause on a new line. E.g., -```rust +```rust,ignore Token::Dimension { value, ref unit, @@ -785,7 +785,7 @@ If every clause in a pattern is *small*, but the whole pattern does not fit on one line, then format the pattern across multiple lines with as many clauses per line as possible. Again, break before a `|`: -```rust +```rust,ignore foo | bar | baz | qux => { ... @@ -795,7 +795,7 @@ per line as possible. Again, break before a `|`: We define a pattern clause to be *small* if it fits on a single line and matches "small" in the following grammar: -``` +```text small: - small_no_tuple - unary tuple constructor: `(` small_no_tuple `,` `)` @@ -817,7 +817,7 @@ if the result fits. Apply the same combining behaviour to any similar expressions which have multi-line, block-indented lists of sub-expressions delimited by parentheses (e.g., macros or tuple struct literals). E.g., -```rust +```rust,ignore foo(bar( an_expr, another_expr, @@ -850,7 +850,7 @@ closure with an explicit block, there are no other closure arguments, and all the arguments and the first line of the closure fit on the first line, use the same combining behavior: -```rust +```rust,ignore foo(first_arg, x, |param| { action(); foo(param) @@ -866,7 +866,7 @@ When writing a range with both upper and lower bounds, if the line must be broken within the range, break before the range operator and block indent the second line: -```rust +```rust,ignore a_long_expression ..another_long_expression ``` diff --git a/src/items.md b/src/items.md index 80904b8..3cc3629 100644 --- a/src/items.md +++ b/src/items.md @@ -8,26 +8,23 @@ 不要自动移动注有 `#[macro_use]` 的模块声明,因为这可能会改变语义。 -## Function definitions +## 函数定义 -In Rust, people often find functions by searching for `fn [function-name]`, so -the formatting of function definitions must enable this. +在 Rust 中,人们经常通过搜索 `fn [function-name]` 来查找函数,因此函数定义的格式必须能够满足这一点。 -The proper ordering and spacing is: +正确的排序和空格位置是: -```rust +```rust,ignore [pub] [unsafe] [extern ["ABI"]] fn foo(arg1: i32, arg2: i32) -> i32 { ... } ``` -Avoid comments within the signature itself. +避免在签名本身中添加注释。 -If the function signature does not fit on one line, then break after the opening -parenthesis and before the closing parenthesis and put each argument on its own -block-indented line. For example, +如果函数签名不能放在一行内,则在开头括号后和结尾括号前分隔,并将每个参数放在自己的缩进行内。例如: -```rust +```rust,ignore fn foo( arg1: i32, arg2: i32, @@ -36,18 +33,17 @@ fn foo( } ``` -Note the trailing comma on the last argument. +注意最后一个参数后面的逗号。 +## 元组和元组结构 -## 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 - -```rust +```rust,ignore struct Bar(Type1, Type2); let x = Bar(11, 22); @@ -62,7 +58,7 @@ Format each variant accordingly as either a struct (but without the `struct` keyword), a tuple struct, or an identifier (which doesn't require special formatting): -```rust +```rust,ignore enum FooBar { First(u32), Second, @@ -77,7 +73,7 @@ If a struct variant is [*small*](index.html#small-items), format it on one line. In this case, do not use a trailing comma for the field list, but do put spaces around each brace: -```rust +```rust,ignore enum FooBar { Error { err: Box, line: u32 }, } @@ -96,7 +92,7 @@ brace on the same line when it fits within the right margin. All struct fields are indented once and end with a trailing comma. The closing brace is not indented and appears on its own line. -```rust +```rust,ignore struct Foo { a: A, b: B, @@ -106,7 +102,7 @@ struct Foo { If and only if the type of a field does not fit within the right margin, it is pulled down to its own line and indented again. -```rust +```rust,ignore struct Foo { a: A, long_name: @@ -121,7 +117,7 @@ space between the braces: `struct Foo;` or `struct Foo {}`. The same guidelines are used for untagged union declarations. -```rust +```rust,ignore union Foo { a: A, b: B, @@ -137,7 +133,7 @@ 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 single-line tuple struct. Don't put spaces around the parentheses or semicolon: -```rust +```rust,ignore pub struct Foo(String, u8); ``` @@ -150,7 +146,7 @@ one line), prefer a proper struct with named fields. For a multi-line tuple struct, block-format the fields with a field on each line and a trailing comma: -```rust +```rust,ignore pub struct Foo( String, u8, @@ -164,7 +160,7 @@ Use block-indent for trait items. If there are no items, format the trait (inclu on a single line. Otherwise, break after the opening brace and before the closing brace: -```rust +```rust,ignore trait Foo {} pub trait Bar { @@ -175,7 +171,7 @@ pub trait Bar { If the trait has bounds, put a space after the colon but not before, and put spaces around each `+`, e.g., -```rust +```rust,ignore trait Foo: Debug + Bar {} ``` @@ -185,7 +181,7 @@ you must break the bounds, put each bound (including the first) on its own block-indented line, break before the `+` and put the opening brace on its own line: -```rust +```rust,ignore pub trait IndexRanges: Index, Output=Self> + Index, Output=Self> @@ -203,7 +199,7 @@ 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 and before the closing brace: -```rust +```rust,ignore impl Foo {} impl Bar for Foo { @@ -215,7 +211,7 @@ Avoid line-breaking in the signature if possible. If a line break is required in a non-inherent impl, break immediately before `for`, block indent the concrete type and put the opening brace on its own line: -```rust +```rust,ignore impl Bar for Foo { @@ -233,12 +229,12 @@ Use spaces around keywords, no spaces around the semicolon. ### Modules -```rust +```rust,ignore mod foo { } ``` -```rust +```rust,ignore mod foo; ``` @@ -249,7 +245,7 @@ semicolon. Use `{}` for the full definition of the macro. -```rust +```rust,ignore macro_rules! foo { } ``` @@ -266,7 +262,7 @@ Do not put spaces before or after `<` nor before `>`. Only put a space after Put a space after each comma. Do not use a trailing comma for a single-line generics clause. -```rust +```rust,ignore fn foo(x: Vec, y: Vec) ... impl SomeType { ... @@ -276,7 +272,7 @@ If the generics clause must be formatted across multiple lines, put each parameter on its own block-indented line, break after the opening `<` and before the closing `>`, and use a trailing comma. -```rust +```rust,ignore fn foo< T: Display, U: Debug, @@ -285,7 +281,7 @@ fn foo< If an associated type is bound in a generic type, put spaces around the `=`: -```rust +```rust,ignore > ``` @@ -305,7 +301,7 @@ comma, unless the clause is terminated with a semicolon. If the `where` clause is followed by a block (or assignment), start that block on a new line. Examples: -```rust +```rust,ignore fn function(args) where T: Bound, @@ -354,7 +350,7 @@ If a component of a `where` clause does not fit and contains `+`, break it before each `+` and block-indent the continuation lines. Put each bound on its own line. E.g., -```rust +```rust,ignore impl IndexRanges for T where T: Index, Output = Self::Output> @@ -370,7 +366,7 @@ where 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: -```rust +```rust,ignore pub type Foo = Bar; // If multi-line is required @@ -382,7 +378,7 @@ Where possible avoid `where` clauses and keep type constraints inline. Where that is not possible split the line before and after the `where` clause (and split the `where` clause as normal), e.g., -```rust +```rust,ignore type VeryLongType where T: U::AnAssociatedType, @@ -396,29 +392,26 @@ where Format associated types like type aliases. Where an associated type has a bound, put a space after the colon but not before: -```rust +```rust,ignore pub type Foo: Bar; ``` - ## 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) Format imports on one line where possible. Don't put spaces around braces. -```rust +```rust,ignore use a::b::c; use a::b::d::*; use a::b::{foo, bar, baz}; ``` - ### Large list imports Prefer to use multiple imports rather than a multi-line import. However, tools @@ -429,8 +422,7 @@ 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 +```rust,ignore // Prefer foo::{long, list, of, imports}; foo::{more, imports}; @@ -442,7 +434,6 @@ foo::{ }; ``` - ### Ordering of imports A *group* of imports is a set of imports on the same or sequential lines. One or @@ -451,10 +442,9 @@ 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 +```rust,ignore use d; use c; @@ -464,7 +454,7 @@ use a; output: -```rust +```rust,ignore use c; use d; @@ -482,7 +472,6 @@ Names in a list import must be sorted ASCIIbetically, but with `self` and 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 Tools must make the following normalisations, recursively: @@ -494,7 +483,6 @@ 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 If there are any nested imports in a list import, then use the multi-line form, @@ -503,7 +491,7 @@ but non-nested imports must be grouped on as few lines as possible. For example, -```rust +```rust,ignore use a::b::{ x, y, z, u::{...}, @@ -516,7 +504,7 @@ use a::b::{ An example: -```rust +```rust,ignore // Un-merged use a::b; use a::c::d; diff --git a/src/statements.md b/src/statements.md index 55cd926..ee3cac9 100644 --- a/src/statements.md +++ b/src/statements.md @@ -4,7 +4,7 @@ 在 `:` 后面和 `=` 的两边(若它们存在的话)空一格。分号前不要空格。 -```rust +```rust,ignore // 一条注释。 let pattern: Type = expr; @@ -15,14 +15,14 @@ let pattern = expr; 如果可能,将声明格式化成一行。如果不可能,则在 `=` 之后尝试分割,如果声明适合在两行中进行。将表达式块缩进。 -```rust +```rust,ignore let pattern: Type = expr; ``` 如果第一行仍不能排在一行上,则在 `:` 之后分行,并使用块缩进。即使在 `:` 后分行后类型还需要多行,也应将第一行放在与 `:` 相同的行上,并遵守[合并规则](expressions.html#combinable-expressions)。 -```rust +```rust,ignore let pattern: Type = expr; @@ -30,7 +30,7 @@ let pattern: 例如: -```rust +```rust,ignore let Foo { f: abcd, g: qwer, @@ -47,7 +47,7 @@ let (abcd, 示例: -```rust +```rust,ignore let foo = Foo { f: abcd, g: qwer, @@ -88,38 +88,28 @@ let Foo { ); ``` -### else blocks (let-else statements) +### else 块(let-else 语句) -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 -the `else` block (i.e. the `let pattern: Type = initializer_expr` portion) -as described [for other let statements](#let-statements). +一个 let 语句可以包含一个 `else` 组件,使其成为一个 let-else 语句。在这种情况下,应始终对 else 块前面的组件(即 `let pattern: Type = initializer_expr` 部分)采用与[其他 let 语句](#let-语句)相同的格式化规则。 -Format the entire let-else statement on a single line if all the following are -true: +如果以下条件都符合,则将整个 let-else 语句格式化为一行: -* the entire statement is *short* -* the `else` block contains only a single-line expression and no statements -* the `else` block contains no comments -* the let statement components preceding the `else` block can be formatted on a single line +- 整个语句很**短** +- `else` 块只包含一个单行表达式,不包含任何语句 +- `else` 块不包含注释 +- `else` 块前面的 let 语句组件可以格式化为单行 -```rust +```rust,ignore let Some(1) = opt else { return }; ``` -Otherwise, the let-else statement requires some line breaks. +否则,let-else 语句需要换行。 -If breaking a let-else statement across multiple lines, never break between the -`else` and the `{`, and always break before the `}`. +如果将 let-else 语句换成多行,切勿在`else` 和 `{` 之间换行,一定要在 `}` 之前换行。 -If the let statement components preceding the `else` can be formatted on a -single line, but the let-else does not qualify to be placed entirely on a -single line, put the `else {` on the same line as the initializer expression, -with a space between them, then break the line after the `{`. Indent the -closing `}` to match the `let`, and indent the contained block one step -further. +如果 `else` 前面的 let 语句组件可以格式化为一行,但 let-else 不符合完全放在一行的条件,则应将 `else {` 放在初始化表达式的同一行,并在两者之间留一个空格,然后在 `{` 之后换行。缩进结尾的 `}` 以匹配 `let`,并将包含的代码块再缩进一步。 -```rust +```rust,ignore let Some(1) = opt else { return; }; @@ -130,30 +120,24 @@ let Some(1) = opt else { }; ``` -If the let statement components preceding the `else` can be formatted on a -single line, but the `else {` does not fit on the same line, break the line -before the `else`. +如果 `else` 前面的 let 语句组件可以在一行中格式化,但 `else {` 不能在同一行中格式化时,则在 `else` 之前换行。 -```rust +```rust,ignore let Some(x) = some_really_really_really_really_really_really_really_really_really_long_name else { return; }; ``` -If the initializer expression is multi-line, put the `else` keyword and opening -brace of the block (i.e. `else {`) on the same line as the end of the -initializer expression, with a space between them, if and only if all the -following are true: +如果初始化表达式为多行,则在且仅在以下所有条件都符合的情况下,将 `else` 关键字和代码块的开头括号(即 `else {`)放在与初始化表达式结尾相同的行上,并在它们之间留一个空格: -* The initializer expression ends with one or more closing - parentheses, square brackets, and/or braces -* There is nothing else on that line -* That line has the same indentation level as the initial `let` keyword. +- 初始化表达式以一个或多个结束括号、方括号和/或大括号结束 +- 该行没有其他内容 +- 该行的缩进级别与初始 `let` 关键字的缩进级别相同 -For example: +例如: -```rust +```rust,ignore let Some(x) = y.foo( "abc", fairly_long_identifier, @@ -166,13 +150,11 @@ let Some(x) = y.foo( } ``` -Otherwise, put the `else` keyword and opening brace on the next line after the -end of the initializer expression, with the `else` keyword at the same -indentation level as the `let` keyword. +否则,将 `else` 关键字和开头括号放在初始化表达式结束后的下一行,`else` 关键字的缩进级别与 `let` 关键字的缩进级别相同。 -For example: +例如: -```rust +```rust,ignore fn main() { let Some(x) = abcdef() .foo( @@ -218,32 +200,28 @@ fn main() { } ``` -## 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 -name, `!`, the delimiters, or the `;`. +在语句位置使用宏时,使用圆括号或方括号作为分隔符,并以分号结束。请勿在名称、`!`、分隔符或 `;` 前后使用空格。 -```rust -// A comment. +```rust,ignore +// 注释 a_macro!(...); ``` +## 语句位置中的表达式 -## Expressions in statement position - -Do not put space between the expression and the semicolon. +表达式和分号之间不要加空格。 -``` +```rust,ignore ; ``` -Terminate all expressions in statement position with a semicolon, unless they -end with a block or are used as the value for a block. +用分号结束语句位置上的所有表达式,除非这些表达式以块结束或用作块的值。 -E.g., +例如: -```rust +```rust,ignore { an_expression(); expr_as_value() @@ -256,10 +234,9 @@ loop { } ``` -Use a semicolon where an expression has void type, even if it could be -propagated. E.g., +表达式为空类型时,即使可以传递,也要使用分号。例如: -```rust +```rust,ignore fn foo() { ... } fn bar() { diff --git a/src/types.md b/src/types.md index c161d57..148437d 100644 --- a/src/types.md +++ b/src/types.md @@ -20,7 +20,7 @@ 尽可能避免在类型中换行。最好在最外层的范围内换行,例如,最好使用以下形式: -```rust +```rust,ignore Foo< Bar, Baz, @@ -29,7 +29,7 @@ Foo< 而不采用: -```rust +```rust,ignore Foo