Rust Style Guide

Motivation - why use a formatting tool?

Formatting code is a mostly mechanical task which takes both time and mental effort. By using an automatic formatting tool, a programmer is relieved of this task and can concentrate on more important things.

Furthermore, by sticking to an established style guide (such as this one), programmers don't need to formulate ad hoc style rules, nor do they need to debate with other programmers what style rules should be used, saving time, communication overhead, and mental energy.

Humans comprehend information through pattern matching. By ensuring that all Rust code has similar formatting, less mental effort is required to comprehend a new project, lowering the barrier to entry for new developers.

Thus, there are productivity benefits to using a formatting tool (such as rustfmt), and even larger benefits by using a community-consistent formatting, typically by using a formatting tool's default settings.

The default Rust style

The Rust Style Guide defines the default Rust style, and recommends that developers and tools follow the default Rust style. Tools such as rustfmt use the style guide as a reference for the default style. Everything in this style guide, whether or not it uses language such as “must” or the imperative mood such as “insert a space ...” or “break the line after ...”, refers to the default style.

This should not be interpreted as forbidding developers from following a non-default style, or forbidding tools from adding any particular configuration options.

Formatting conventions

Indentation and line width

  • Use spaces, not tabs.
  • Each level of indentation must be 4 spaces (that is, all indentation outside of string literals and comments must be a multiple of 4).
  • The maximum width for a line is 100 characters.

Block indent

Prefer block indent over visual indent:

// Block indent
a_function_call(
    foo,
    bar,
);

// Visual indent
a_function_call(foo,
                bar);

This makes for smaller diffs (e.g., if a_function_call is renamed in the above example) and less rightward drift.

Trailing commas

In comma-separated lists of any kind, use a trailing comma when followed by a newline:

function_call(
    argument,
    another_argument,
);

let array = [
    element,
    another_element,
    yet_another_element,
];

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,

fn foo() {
    let x = ...;

    let y = ...;
    let z = ...;
}

fn bar() {}
fn baz() {}

Sorting

In various cases, the default Rust style specifies to sort things. If not otherwise specified, such sorting should be “version sorting”, which ensures that (for instance) x8 comes before x16 even though the character 1 comes before the character 8. (If not otherwise specified, version-sorting is lexicographical.)

For the purposes of the Rust style, to compare two strings for version-sorting:

  • Compare the strings by (Unicode) character lexicographically, finding the index of the first differing character. (If the two strings do not have the same length, this may be the end of the shorter string.)
  • For both strings, determine the longest sequence of ASCII digits that either contains or ends at that index. (If either string doesn't have such a sequence of ASCII digits, fall back to comparing the strings lexicographically.)
  • Compare the numeric values of the number specified by the sequence of digits. (Note that an implementation of this algorithm can easily check this without accumulating copies of the digits or converting to a number: after skipping leading zeroes, longer sequences of digits are larger numbers, and equal-length sequences of digits can be sorted lexicographically.)
  • If the numbers have the same numeric value, the one with more leading zeroes comes first.

Note that there exist various algorithms called “version sorting”, which differ most commonly in their handling of numbers with leading zeroes. This algorithm does not purport to precisely match the behavior of any particular other algorithm, only to produce a simple and satisfying result for Rust formatting. (In particular, this algorithm aims to produce a satisfying result for a set of symbols that have the same number of leading zeroes, and an acceptable and easily understandable result for a set of symbols that has varying numbers of leading zeroes.)

As an example, version-sorting will sort the following symbols in the order given: x000, x00, x0, x01, x1, x09, x9, x010, x10.

Module-level items

Statements

Expressions

Types

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:

// A comment on an item.
struct Foo { ... }

fn foo() {} // A comment after an item.

pub fn foo(/* a comment before an argument */ 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:

// This comment goes up to the ................................. 80 char margin.

{
    // This comment is .............................................. 80 chars wide.
}

{
    {
        {
            {
                {
                    {
                        // This comment is limited by the ......................... 100 char margin.
                    }
                }
            }
        }
    }
}

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.

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.

#[repr(C)]
#[foo(foo, bar)]
#[long_multi_line_attribute(
    split,
    across,
    lines,
)]
struct CRepr {
    #![repr(C)]
    x: f32,
    y: f32,
}

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:

// Normal formatting
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.

Non-formatting conventions

Cargo.toml conventions

Principles used for deciding these guidelines