Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a crate in a Cargo project errors with "maybe a missing extern crate"

I started learning Rust today, but I am stuck at this step. I want use the rand crate in my project, so I updated my Cargo.toml as suggested in the tutorial:

[package]
name = "guessing_game"
version = "0.1.0"
authors = ["Novice <[email protected]>"]

[dependencies]
rand = "0.3.14"

Importing it in my code as:

use rand::Rng;

It gives this error:

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

Am I missing something?


I added edition = "2018" as suggested:

Cargo.toml:

[package]
name = "guessing_game"
version = "0.1.0"
authors = ["Novice <[email protected]>"]
edition = "2018"

[dependencies]
rand = "0.3.14"

Cargo build now gives:

$ 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.

I updated rust using rustup update and then added extern crate rand; to my main.rs. Now it's working as expected.

The program runs but in my vscode problems tab its still showing the error -

error[E0432]: unresolved import `rand`
 --> src/main.rs:1:5
  |
1 | use rand::Rng;
  |     ^^^^ maybe a missing `extern crate rand;`?
like image 978
Bopsi Avatar asked Dec 31 '18 09:12

Bopsi


1 Answers

The quick fix is to add

edition = "2021"

to your Cargo.toml, above the [dependencies] line.

Explanation

There are three major editions of Rust: Rust 2015, 2018, and 2021. Rust 2021 is recommended for new code, but since Rust needs to be backward compatible, you have to opt in to use it.

In Rust 2015, you had to write an extern crate statement before using anything outside of std. That's where the error message comes from. But you don't have to do that in Rust 2018 or 2021 anymore, which is why setting the edition fixes it.

There are many more changes in Rust 2021; if you're interested, you can read about them in the edition guide.

like image 197
Lambda Fairy Avatar answered Dec 04 '22 23:12

Lambda Fairy