Sub topic 4
Opting out of formatting for specific items
rustfmt works well because it has no exceptions by default. Every file is laid out the same way, and nobody argues about style in code review. A few kinds of code read better when a human lays them out, though. Examples are lookup tables, aligned constants, and macro-heavy data. This chapter covers how to tell rustfmt to leave those spots alone, how far each opt-out reaches, and how to avoid overusing it.
This chapter assumes you can run cargo fmt and have a project with a rustfmt.toml, as covered in the previous two chapters.
Why you would skip formatting
Consider a 3x3 identity matrix written as a grid. Each row sits on its own line, and the columns line up. The layout shows the structure of the data. If rustfmt collapses it, the code still compiles, but the reader loses the visual pattern. Typically rustfmt would turn the grid into a single long line, or wrap it at arbitrary points.
Good candidates for skipping:
- Tables of numbers, flags, or opcodes where column alignment carries meaning.
- Bit masks and protocol constants aligned by field.
- Data passed to a custom macro that rustfmt cannot parse as normal Rust.
- Generated code that you never edit by hand.
Poor candidates:
- Code you simply dislike the formatting of. Change a setting in
rustfmt.tomlinstead, so the choice applies consistently. - Long functions you did not want to reformat during a large diff. Format the whole file once in a separate commit.
The `#[rustfmt::skip]` attribute
#[rustfmt::skip] is a tool attribute. The compiler ignores it, and rustfmt reads it. It works on stable Rust with no configuration. Put it directly above the item you want preserved.
#[rustfmt::skip]
const IDENTITY: [[u8; 3]; 3] = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
fn main() {
for row in IDENTITY {
println!("{row:?}");
}
}Run cargo fmt on this file and the constant stays as written. The rest of the file is still formatted normally. If you remove the attribute and run cargo fmt again, rustfmt rewrites the grid.
The attribute removes only the formatting of the item it is attached to. It does not affect Clippy, and it does not change how the compiler treats the code.
What the attribute can be attached to
The attribute follows Rust's normal rules for where attributes are allowed. These targets work:
| Target | Example | Effect |
|---|---|---|
| Constant or static | `#[rustfmt::skip] const T: ...` | The whole declaration is preserved. |
| Function | `#[rustfmt::skip] fn f() { ... }` | The signature and body are preserved. |
| `impl` block or `struct` | `#[rustfmt::skip] struct S { ... }` | Everything inside is preserved. |
| Module declaration | `#[rustfmt::skip] mod generated;` | The module's contents are not formatted. |
| Statement | `#[rustfmt::skip] let x = ...;` | Only that statement is preserved. |
The module row deserves detail. Writing #[rustfmt::skip] on mod generated; in the parent file tells rustfmt not to descend into generated.rs. This is the usual way to exclude generated code, such as output from a build script or a code generator.
You can also skip a single statement inside an otherwise formatted function:
fn checksum(data: &[u8]) -> u32 {
#[rustfmt::skip]
let weights = [
1, 3, 5, 7,
11, 13, 17, 19,
];
data.iter()
.zip(weights.iter().cycle())
.map(|(b, w)| u32::from(*b) * w)
.sum()
}
fn main() {
println!("{}", checksum(&[1, 2, 3]));
}The let weights statement keeps its two-column-by-four layout. The iterator chain below it is still formatted by rustfmt.
Where it does not work
The compiler decides where attributes are legal, not rustfmt. Attributes on arbitrary expressions, such as a function argument or one operand of a +, are rejected or unstable. If you need to protect part of an expression, move it into a let statement and attach the attribute to the statement. Alternatively, move it into a separate const or helper function.
Skipping only macros or attributes
Sometimes the problem is not an item but a particular macro. rustfmt formats the arguments of a macro call only if they parse as ordinary Rust expressions. For macros that take table-like arguments, the result may be awkward or inconsistent between runs of different rustfmt versions.
Rather than skipping the whole enclosing item, you can name the macro. The skip::macros form takes a list of macro names. It applies to the item it is attached to, including everything nested inside it.
macro_rules! matrix {
($([$($x:expr),*]),*) => { [$([$($x),*]),*] };
}
#[rustfmt::skip::macros(matrix)]
fn rotation() -> [[i32; 2]; 2] {
matrix![
[ 0, -1],
[ 1, 0]
]
}
fn main() {
println!("{:?}", rotation());
}The rest of rotation is formatted as usual. Only calls to matrix! are left exactly as written.
A matching form, #[rustfmt::skip::attributes(name)], tells rustfmt to leave attributes with the given names alone. It is useful for attributes from derive crates or frameworks that carry long, hand-wrapped argument lists. You can pass several names separated by commas:
#[rustfmt::skip::attributes(custom_attr, other_attr)]
mod framework_types {
// Items here may carry #[custom_attr(...)] and #[other_attr(...)]
}Use the narrower forms when you can. A skip for one macro name is safer than a skip for a whole module, because the surrounding code still gets formatted.
Choosing the right scope
The attribute forms differ in how much code they leave unformatted. This diagram helps pick the narrowest one.
Interaction with `cargo fmt --check`
Skipped items are invisible to the check. Run this command in CI:
cargo fmt --all -- --checkIf an item has #[rustfmt::skip], the check never reports it, however it is laid out. A skipped table can therefore have trailing whitespace, a mix of tabs and spaces, or inconsistent alignment, and the check still passes. Review skipped code by eye in pull requests. The tool will not catch mistakes there.
Config-level alternatives and their limits
If you want to exclude files rather than annotate items, you might look at the ignore option in rustfmt.toml. That option is unstable, so it only works with a nightly rustfmt. The chapter on configuration listed only stable options for that reason. For a stable workflow, #[rustfmt::skip] on the module declaration is the portable way to exclude a file.
Other configuration options can solve the underlying problem without any annotation. For example, a wider max_width may stop a table from wrapping. This keeps the formatter in control and the code consistent. Try configuration first and annotations second.
Older markers you may still see
Older codebases sometimes contain a // rustfmt-skip comment or the form #[cfg_attr(rustfmt, rustfmt_skip)]. These come from before tool attributes were stable. Current rustfmt expects #[rustfmt::skip]. If you meet the old forms, replace them. A modern toolchain may not honor them, and the table beneath them can be reformatted unexpectedly.
Common mistakes
- Placing the attribute on the wrong item. An attribute above a
useline affects only that line. If your table is a few lines below, it is still formatted. - Using a skip to dodge a formatting error. If rustfmt fails or reports that it could not format a line, the cause is often a line that exceeds
max_widthin a string or comment. Skipping hides the problem. Shorten the line, or accept that rustfmt leaves it alone. - Skipping a module and forgetting it. After a generated file is excluded, edits made to it by hand are never formatted, and nobody notices the drift.
- Expecting Clippy to follow the attribute.
rustfmt::skiphas no effect on lints. A skipped function can still trigger Clippy warnings. - Reaching for expression-level attributes. If the compiler reports that attributes on expressions are experimental, lift the code into a statement or item.
Verifying your skip works
A quick workflow when adding a skip:
- Add the attribute and save.
- Run
cargo fmtand confirm withgit diffthat the skipped item is unchanged. - Break the layout on purpose, for example by adding extra spaces, and run
cargo fmtagain. The extra spaces should remain. This confirms the attribute is attached to the right item. - Undo the experiment.
This also protects against a typo, such as #[rustfmt::skp]. A misspelled tool attribute is a compile error for tools the compiler knows about, but checking behavior costs seconds and catches misplaced attributes as well.
Exercise
A project keeps a hand-aligned table in src/opcodes.rs, declared in main.rs as mod opcodes;. A colleague wants to stop rustfmt from touching the whole file, but only the OPCODES constant is aligned by hand. What is the narrowest correct change, and why does cargo fmt --all -- --check still pass if someone later mangles the constant's spacing?
Show answer
Put #[rustfmt::skip] directly above the OPCODES constant inside src/opcodes.rs, instead of skipping the mod opcodes; declaration, so the rest of the file stays formatted. The check still passes after the spacing is mangled because rustfmt never inspects a skipped item, so it has no formatted version to compare against. The layout of skipped code must be reviewed by hand.
Exercise
You have a function that calls a custom macro table! with aligned arguments, and the rest of the function should stay formatted. Which attribute do you write on the function, and what does it leave alone?
Show answer
Write #[rustfmt::skip::macros(table)] above the function. It leaves calls to table! inside the function exactly as written. The rest of the function body is still formatted by rustfmt.