Crate naming: foo-bar vs foo_bar

Cargo allows naming crates with either hyphens or underscores. But to access their symbols from within a Rust program, you must always use underscores. This creates an annoying many-to-one situation: The "foo-bar" and "foo_bar" crates have overlapping symbol namespaces.
So what's the best policy here? Should we always use underscores in the crate name so it will match the symbol namespace? Or always use hyphens, because they look better? crates.io shows plenty of crates that use both naming schemes.

1 Like

I usually use hyphens.

This creates an annoying many-to-one situation: The "foo-bar" and "foo_bar" crates have overlapping symbol namespaces.

Actually, it doesn't; crates.io will not allow you to publish packages that overlap this way. (And outside of crates.io or another registry, nothing is enforcing any uniqueness in package naming anyway.)

In general, crate names in Rust code are less global than they look; you can rename a dependency any way you like (either in Cargo.toml by specifying the package key, or in Rust by using extern crate foo_bar as foobar;), and you have to do this if you find yourself in the position of using two versions of the same crate (e.g. to implement two versions of traits). It's even possible for a package to ship with a different default library crate name — for example, I've seen a package projectname-libname contain a crate named libname.

So what's the best policy here? Should we always use underscores in the crate name so it will match the symbol namespace? Or always use hyphens, because they look better?

Unfortunately, there is no consensus.

Personally, I use hyphens because I think that hyphens are better typographically/linguistically, as well as being easier to type, and it is something of an accident of history that most programming languages don't allow you to use hyphens in identifiers — so take advantage of hyphens when technical considerations permit.

(And in naming a command-line tool, it's typical to use hyphens if anything, and domain names use hyphens and not underscores…)

But it's entirely reasonable to consider me foolishly inconsistent here.

5 Likes

I like underscores for consistency, so searching for some_crate in a repository will bring it up in Cargo.toml as well and such, it's also nice that double-clicking the name in a browser selects the entire name instead of breaking at the hyphen for copying or whatever.

Those are pretty minor reasons though. Now that cargo add is included by default I don't feel that strongly about it, since cargo add some_crate and cargo add some-crate will both work regardless of what the crate actually uses.

1 Like

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.