One import per line is best

Rust has a feature where if you import two things from the same module you can abbreviate it like this:

use mypkg::{MyStruct1, MyStruct2};

If you prefer, you can keep them separate, like this:

use mypkg::MyStruct1;
use mypkg::MyStruct2;

I do prefer. Strongly.

Advantages of the abbreviated style

  • Fewer lines of code
  • Fewer characters of code

Advantages of the separated style

  • Simpler diffs with fewer conflicts. If I add or delete an import, it adds or removes exactly one line. This makes it easier to read diffs and reduces conflicts when merging.
  • Less diff noise when lines overflow. Adding or removing an import is less likely to cause the code formatter to reflow the line. Reflows make it hard to see which dependencies have changed when reading a diff.
  • Easier searching. If I’m trying to find out where a particular type is used I can search for its full path, and my search will find all the places I import it.
  • Easier to read. I find line of code like this really hard to read:
    use crate::{
        gossiping::{GossipRequest, GossippedSecret, SecretInfo},
        identities::{ReadOnlyDevice, ReadOnlyUserIdentities},
        olm::{OutboundGroupSession, PrivateCrossSigningIdentity},

I think the separated style is much better, and I wish Rustfmt defaulted to using it. What do you think?

rustfmt config

To enforce my preferred style, include this in your rustfmt.toml:

imports_granularity = Item

(Rustfmt docs)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.