Formatting

Key Tools

TopicRust Crates
Code Formatterrustfmt is the standard Rust code formatter.
Formatting ConfigurationConfiguration is done through rustfmt.toml files.
IntegrationMost IDEs have built-in rustfmt integration.

Format your Rust code with rustfmt

rustfmt_nightly-github cat-development-tools

Install rustfmt with rustup component add rustfmt

rustfmt <filename e.g. lib.rs> <main.rs> ... # or for the whole project cargo fmt

Using --check instructs rustfmt to exit with an error code if the input is not formatted correctly (useful for CI).

cargo fmt --all -- --check

Configure rustfmt

Create a rustfmt.toml in the project root folder. For example,

edition = "2021" style_edition = "2021" unstable_features = true newline_style = "Unix" #max_width = 100 # default: 100 use_small_heuristics = "Max" format_code_in_doc_comments = true indent_style = "Visual" # Imports imports_granularity = "Item" # or "Crate" or "Module" imports_layout = "Vertical" group_imports = "StdExternalCrate" # Comments comment_width = 100 wrap_comments = true normalize_comments = true normalize_doc_attributes = true # Functions fn_params_layout = "Compressed" # Impl reorder_impl_items = true # Structs use_field_init_shorthand = true # Macros use_try_shorthand = true

List config options with

rustfmt --help=config

Use Attributes to Skip Code Formatting in Your Code

rustfmt_nightly-github cat-development-tools

For things you do not want rustfmt to mangle, use #[rustfmt::skip] , #[rustfmt::skip::macros(macro_name)] , or #![rustfmt::skip::attributes(custom_attribute)]