Guard lines from rustfmt

Is there a way to guard certain lines from modification by rustfmt?

My use case is an array that holds the elements of a matrix that represents characteristics about a 2D state space, so retaining my custom formatting

let s = [
    1, 2, 3,
    4, 5, 6,
    7, 8, 9,
];

...is much more intuitive when reviewing and sharing the code than the result of rustfmt:

let s = [1, 2, 3, 4, 5, 6, 7, 8, 9];

Applying #[rustfmt::skip] to an item will keep rustfmt from touching it, though if you want to limit the skipping to just a few lines rather than something like an entire function, you'll need to satisfy the requirements for what attributes can be applied to.

2 Likes

A narrower-scoped but less self-explanatory tool is to add a line comment to each line:

let s = [
    1, 2, 3, //
    4, 5, 6, //
    7, 8, 9, //
];

Each comment is a place where rustfmt won't remove the line break. This preserves your matrix formatting, but still allows rustfmt to manage indentation and spacing, whereas #[rustfmt::skip] will cause it to not even change indentation.

8 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.