Coming to Rust most recently from the JavaScript world I was used to code style being something that was wildly debated and something that would change from project to project I worked on.
In Rust land, however, things are quite different.
For one thing the strong type system and the compiler's borrow, ownership and lifetime checking simply makes some bad code style from JavaScript impossible in Rust.
There is also a whole different level of consensus in the Rust camp on things like variable naming (snake_case), trailing commas (yes), indentation (4 spaces). And the language has no automatic semicolon insertion so there is no semicolon debate.
It helps that there is an official page in the Rust docs with style guidelines https://doc.rust-lang.org/1.12.0/style/README.html.
A few of these rules are checked by the compiler itself, while the rest is left to the excellent Rustfmt tool.
Rustfmt
To install Rustfmt, simply run (assuming you have rustup installed):
rustup run nightly cargo install rustfmt
Rustfmt has several modes you can run it in. To simply list the problems, as a linter might, run it in diff
mode.
cargo fmt -- --write-mode=diff
The default if you just run cargo fmt
is to use the replace
mode, which will fix all code style issues, and make a .bk
backup file for every changed file.
Since I just want something that keeps all code in the same style I use the overwrite
mode:
cargo fmt -- --write-mode=overwrite
Install Rustfmt in Atom
I don't actually run that command though, I have Rustfmt integrated into Atom, so that it fixes my code style everytime I save.
To use Rustfmt in Atom you use the atom-beautify
package.
Go to Atom > Preferences > Install
and search for atom-beautify
.
Install it and then click Settings
, you'll have a list of languages there, scroll down to Rust:
Make sure Beautify on save
is checked and enter the path rustfmt below. The easiest way to get the path is to run which rustfmt
in your terminal.
Having Rustfmt format your code every time you save is like having a buddy proofread your code and fix it for you. 🤓
If you don't use Atom, there are Rustfmt integrations for other editors. Check the Rustfmt readme for more info.
Skipping code
If you know you are going to write weird looking code but want to keep it that way you can add #[cfg_attr(rustfmt, rustfmt_skip)]
before the your code you want to keep intact.
Configuring Rustfmt
I'm perfectly happy using the default settings, and I think it's a strength to keep it that way, but if you absolutely can't stand one of the things Rustfmt does it is very configurable.
Create a rustfml.toml
in the root of your project and add any rule changes you want. Run rustfmt --config-help
to get a list of all rules and possible values.
This would be the contents of rustfmt.toml
if you can't stand trailing commas in structs for example:
struct_trailing_comma = "Never"