在Cargo项目中使用一个crate出现错误,提示可能缺少extern crate。

22

我今天开始学习Rust,但我卡在了这一步。我想在我的项目中使用rand crate,所以我按照教程建议更新了我的Cargo.toml:

[package]
name = "guessing_game"
version = "0.1.0"
authors = ["Novice <novice.coder@gmail.com>"]

[dependencies]
rand = "0.3.14"

在我的代码中导入它:

use rand::Rng;

它会报以下错误:

error[E0432]: unresolved import `rand`
 --> src/main.rs:1:5
  |
1 | use rand::Rng;
  |     ^^^^ maybe a missing `extern crate rand;`?

我有什么遗漏吗?


我按建议添加了 edition = "2018"

Cargo.toml:

[package]
name = "guessing_game"
version = "0.1.0"
authors = ["Novice <novice.coder@gmail.com>"]
edition = "2018"

[dependencies]
rand = "0.3.14"

Cargo build现在会给出:

$ cargo build --verbose
   Fresh libc v0.2.45
   Fresh rand v0.4.3
   Fresh rand v0.3.22
 Compiling guessing_game v0.1.0 (/home/bappaditya/projects/guessing_game)
 Running `rustc --edition=2018 --crate-name guessing_game src/main.rs --color always --crate-type bin --emit=dep-info,link -C debuginfo=2 -C metadata=4d1c2d587c45b4
c6 -C extra-filename=-4d1c2d587c45b4c6 --out-dir 
/home/bappaditya/projects/guessing_game/target/debug/deps -C 
incremental=/home/bappaditya/projects/guessing_game/target
/debug/incremental -L 
dependency=/home/bappaditya/projects/guessing_game/target/debug/deps -- 
extern rand=/home/bappaditya/projects/guessing_game/target/debug/deps/libra
nd-78fc4b142cc921d4.rlib`
error: Edition 2018 is unstable and only available for nightly builds of rustc.

我使用 rustup update 更新了 Rust,并在 main.rs 中添加了 extern crate rand;。现在它按预期工作。
程序已经运行,但在我的 vscode 问题标签中仍然显示错误 -
error[E0432]: unresolved import `rand`
 --> src/main.rs:1:5
  |
1 | use rand::Rng;
  |     ^^^^ maybe a missing `extern crate rand;`?

4
您提供的链接中有edition = "2018",您是怎么忽略它的? - Stargateur
我将其删除了,因为它产生了错误 - 错误:2018版不稳定,仅适用于rustc的夜间构建。 - Bopsi
3
更新你的编译器。 - Boiethios
1
如果你无法更新编译器,另一种选择是在 main.rs 的开头添加 extern crate rand;,正如 @LambdaFairy 在他们的回答中提到的。 - rodrigo
extern crate rand 仍然会产生相同的错误。 - Bopsi
显示剩余2条评论
1个回答

52

快速解决方法是添加

edition = "2021"

[dependencies]行上面添加到您的 Cargo.toml 文件中。

说明

Rust有三个主要的版本:Rust 2015、2018和2021。建议新代码使用Rust 2021,但由于Rust需要向后兼容,您必须选择使用它。

在Rust 2015中,您必须在使用std之外的任何内容之前编写一个extern crate语句。这就是错误信息的来源。但在Rust 2018或2021中,您不再需要这样做,这就是设置版本能够解决此问题的原因。

Rust 2021 中有更多变化;如果您感兴趣,可以在版本指南中阅读有关它们的信息。


现在我遇到了这个错误 - 错误:2018版不稳定,仅适用于rustc的夜间构建。我正在更新问题。 - Bopsi
2
@Bopsi,如果你已经安装了之前的版本,可以通过rustup update更新到2018版。现在它已经稳定了,所以在成功更新后不应该出现任何错误。这是参考链接 - Akiner Alkan
使用 rustup 命令更新 Rust 后,我在 main.rs 中添加了 extern crate rand;。现在它可以正常工作了。 - Bopsi
哦我的天啊,我一直在拔头发,试图理解为什么我的所有板条箱都找不到。现在我成了反对Rust的人。但至少我会完成我的项目。 - Pedro Vernetti

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