E0432 rust module_error ai_generated true

错误[E0432]:无法解析导入 `my-crate` -- 在 crate 根中找不到 `my-crate`

error[E0432]: unresolved import `my-crate` -- could not find `my-crate` in the crate root

ID: rust/e0432-unresolved-import-crate-name-hyphen

其他格式: JSON · Markdown 中文 · English
98%修复率
90%置信度
1证据数
2023-02-14首次发现

版本兼容性

版本状态引入弃用备注
rustc 1.56.0 active
rustc 1.63.0 active
rustc 1.70.0 active

根因分析

Rust 中带连字符的 crate 名称在代码中会自动转换为下划线;在 use 语句中应使用 `my_crate` 而不是 `my-crate`。

English

Rust crate names with hyphens are automatically converted to underscores in code; use `my_crate` instead of `my-crate` in use statements.

generic

官方文档

https://doc.rust-lang.org/error_codes/E0432.html

解决方案

  1. 在所有 use 语句中将连字符替换为下划线:`use my_crate::SomeType;`
  2. 在 Cargo.toml 中使用 `package` 键重命名:`my_crate = { package = "my-crate", version = "1.0" }`,然后以 `my_crate` 导入。
  3. 如果需要,使用 `extern crate my_crate as my_crate;` 用于遗留代码。

无效尝试

常见但无效的做法:

  1. 95% 失败

    extern crate also uses the underscore convention. The hyphen is only valid in Cargo.toml dependency names, not in code.

  2. 70% 失败

    Cargo.toml dependency names can have hyphens, but the crate name in Rust source is always underscores. Renaming in Cargo.toml is unnecessary.

  3. 95% 失败

    Hyphens are not valid in Rust identifiers. Use underscores instead.