Rust找不到crate

46
我正在尝试创建一个Rust模块,然后从另一个文件中使用它。这是我的文件结构:
matthias@X1:~/projects/bitter-oyster$ tree
.
├── Cargo.lock
├── Cargo.toml
├── Readme.md
├── src
│   ├── liblib.rlib
│   ├── lib.rs
│   ├── main.rs
│   ├── main.rs~
│   └── plot
│       ├── line.rs
│       └── mod.rs
└── target
    └── debug
        ├── bitter_oyster.d
        ├── build
        ├── deps
        ├── examples
        ├── libbitter_oyster.rlib
        └── native

8 directories, 11 files

This is Cargo.toml:

[package]
name = "bitter-oyster"
version = "0.1.0"
authors = ["matthias"]

[dependencies]

这是 main.rs 文件:
extern crate plot;

fn main() {
    println!("----");
    plot::line::test();
}

这是lib.rs文件:
mod plot;

这是 plot/mod.rs 文件。

mod line;

这是plot/line.rs

(关于IT技术的内容)
pub fn test(){
    println!("Here line");
}

当我尝试使用cargo run编译我的程序时,我会得到以下错误:

   Compiling bitter-oyster v0.1.0 (file:///home/matthias/projects/bitter-oyster)
/home/matthias/projects/bitter-oyster/src/main.rs:1:1: 1:19 error: can't find crate for `plot` [E0463]
/home/matthias/projects/bitter-oyster/src/main.rs:1 extern crate plot;

我该如何编译我的程序?从在线文档来看,这应该是可行的,但实际上并不起作用。

5个回答

33

除了之前给出的答案,当你尝试在另一个项目中引用一个编译为cdylib文档)的库时,可能会产生这个错误。我通过将要重复使用的代码分离到一个常规的lib项目中解决了此问题。


9
例如,在使用PY03时需要cdylib,为了解决这个问题,我设置了crate-type = ["cdylib", "lib"],这意味着该库既可以用于Python编译,也可以在其他Rust库中使用。 - sam

29
如果您看到此错误信息:
error[E0463]: can't find crate for `PACKAGE`
  |
1 | extern crate PACKAGE;
  | ^^^^^^^^^^^^^^^^^^^^^ can't find crate

可能是因为您没有在Cargo.toml的依赖项列表中添加所需的crate:

[dependencies]
PACKAGE = "1.2.3"

请参阅Cargo文档中有关指定依赖项的说明

3
注意:如果你在谷歌搜索这个错误,它会把你带到这里,所以我希望这篇翻译能对其他人有所帮助! - Andy Hayden
1
如何确定要指定哪个版本的crate?是否总有一个地方可以查看发布说明以获取线索? - James Jones
1
通常情况下,crates.io 上的说明就是你想要的(最新版本)https://crates.io/crates/serde,你还可以查看依赖关系等。@JamesJones - Andy Hayden

23

您遇到了以下问题:

  1. 您需要在 main.rs 中使用 extern crate bitter_oyster;,因为生成的二进制文件使用了您的 crate,而该二进制文件不是它的一部分。

  2. 此外,请在 main.rs 中调用 bitter_oyster::plot::line::test(); 而不是 plot::line::test();plotbitter_oyster crate 中的一个模块,例如 line。 您正在使用其完全限定名称引用 test 函数。

  3. 确保每个模块在其完全限定名称中都是公开的。 您可以使用 pub 关键字使模块公开,例如 pub mod plot;

您可以在此处找到有关 Rust 模块系统的更多信息:https://doc.rust-lang.org/book/crates-and-modules.html

您的模块结构的工作副本如下:

src/main.rs:

extern crate bitter_oyster;

fn main() {
    println!("----");
    bitter_oyster::plot::line::test();
}

src/lib.rs:

pub mod plot;

src/plot/mod.rs:

pub mod line;

src/plot/line.rs :

pub fn test(){
    println!("Here line");
}

1

当我将我的crate导入[dev-dependencies]而不是[dependencies]时,出现了此问题。


0
这种情况可能发生在特定的板条箱未启用某些“功能开关”的情况下。不幸的是,这些功能开关有时可能没有文档说明。当所需的功能标志丢失时,它们会显示相同的错误(“找不到板条箱”)。
我正在使用 diesel,并尝试使用 BigInteger:

错误的

diesel = { version = "2.0.3", features = ["postgres", "chrono", "r2d2", "serde_json", "biginteger"] }

正确:

diesel = { version = "2.0.3", features = ["postgres", "chrono", "r2d2", "serde_json", "numeric"] }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接