【问题标题】:Why is changing hyphenated crate names to underscored names possible and what are the rules for naming under such ambiguous scenarios?为什么可以将带连字符的 crate 名称更改为带下划线的名称,在这种模棱两可的情况下命名规则是什么?
【发布时间】:2020-03-22 00:55:32
【问题描述】:

我创建了一个新的 Cargo 项目: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]

我已经搜索并看到了许多讨论是否应允许在 crate 或包的名称中使用连字符,但没有链接提及解决方案。

我看到的是 crate 名称 hyphen-crate 自动转换为 hyphen_crate 并成功编译和测试。

【问题讨论】:

  • 为什么有可能?包名称中允许使用连字符,但它们在内部被转换为下划线,因为连字符在Rust identifiers 中不是有效字符。
  • @Herohtar 把它放在答案中并链接到一个来源,你就会得到一个赞成票。在我看来,这是 OP 真正要求的唯一信息。
  • 帮助每个 Rust 初学者,不要在 crate 名称中使用连字符:p

标签: rust rust-cargo


【解决方案1】:

包名称中允许使用连字符,但它们在内部被转换为下划线,因为连字符不是Rust identifiers 中的有效字符。

似乎这种自动转换并非总是如此,带有连字符的 crate 必须手动重命名才能导入它们;例如。 extern crate "hyphen-crate" as hyphen_crate;。有关详细信息,请参阅Hyphens Considered Harmful RFC

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 2011-02-10
相关资源
最近更新 更多