在货运项目中使用板条箱错误"maybe a missing extern crate"



我今天开始学习 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 --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,然后将extern crate rand;添加到我的 main.rs 中。现在它按预期工作。

程序运行,但在我的 vscode 问题选项卡中,它仍然显示错误 -

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

快速解决方法是添加

edition = "2021"

到您的Cargo.toml,在[dependencies]线上方。

解释

Rust

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

在 Rust 2015 中,在使用 std 以外的任何内容之前,您必须编写一个 extern crate 语句。这就是错误消息的来源。但是您不必再在 Rust 2018 或 2021 中这样做了,这就是设置版本可以修复它的原因。

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

最新更新