问题描述
我创建了一个新的 Cargo 项目:cargo new --lib hyphen-crate
.
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.
我看到的是包名 hyphen-crate
自动转换为 hyphen_crate
并且它编译和测试成功.
What I see is that the crate name hyphen-crate
is automatically transformed to hyphen_crate
and it compiles and tests successfully.
推荐答案
包名中允许使用连字符,但在内部将它们转换为下划线,因为连字符在 Rust 标识符.
Hyphens are allowed in package names, but they are converted to underscores internally, because hyphens are not valid characters in Rust identifiers.
似乎这种自动转换并非总是如此,并且必须手动重命名带有连字符的 crate 才能导入它们;例如.extern crate "hyphen-crate" as hyphen_crate;
.请参阅被视为有害的连字符 RFC 了解一些细节.
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.
这篇关于为什么可以将带连字符的 crate 名称更改为带下划线的名称,在这种模棱两可的情况下命名规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!