Why is changing hyphenated crate names to underscored names possible and what are the rules for naming under such ambiguous scenarios?

Viewed 1984

I created a new Cargo project: cargo new --lib hyphen-crate.

src/lib.rs

pub fn add(a: u32, b: u32) -> u32 {
    a + b
}

tests/addition.rs

use hyphen_crate::add;

#[test]
fn addition_test() {
    assert_eq!(5, add(2, 3));
}

Cargo.toml

[package]
name = "hyphen-crate"
version = "0.1.0"
authors = ["xolve"]
edition = "2018"

[dependencies]

I have searched and seen many discussions if hyphens should be allowed in names of crates or packages, but no link mentions a solution.

What I see is that the crate name hyphen-crate is automatically transformed to hyphen_crate and it compiles and tests successfully.

1 Answers

Hyphens are allowed in package names, but they are converted to underscores internally, because hyphens are not valid characters in Rust identifiers.

It seems that this automatic conversion was not always the case, and crates with hyphens had to be manually renamed in order to import them; eg. extern crate "hyphen-crate" as hyphen_crate;. See the Hyphens Considered Harmful RFC for some details on that.

Related