I think that use
is used to import identifiers into the current scope and extern crate
is used to declare an external module. But this understanding (maybe wrong) doesn't make any sense to me. Can someone explain why Rust has these two concepts and what are the suitable cases to use them?
2 Answers
extern crate foo
indicates that you want to link against an external library and brings the top-level crate name into scope (equivalent to use foo
). As of Rust 2018, in most cases you won't need to use extern crate
anymore because Cargo informs the compiler about what crates are present. (There are one or two exceptions)
use bar
is a shorthand for referencing fully-qualified symbols.
Theoretically, the language doesn't need use
— you could always just fully-qualify the names, but typing std::collections::HashMap.new(...)
would get very tedious! Instead, you can just type use std::collections::HashMap
once and then HashMap
will refer to that.
-
10Without
use
, we couldn't even havestd
as the facade it is. Either we'd have a single monolithic standard library crate, or everyone would be dealing with the fact thatString
is actuallycollections::string::String
.– user395760Commented Apr 2, 2015 at 11:11
Since Rust 2018 you're only required to add external dependencies to your Cargo.toml
, so you no longer need to use extern crate foo
.
use
works the same as before.
Read more in the official documentation.
-
2Even if it's not necessary, isn't there a benefit in separating external crates from standard ones? Like
extern crate failure;
butuse std::error::Error
Commented Mar 8, 2020 at 19:18 -
5@PaulRazvanBerg You mean just to clarify which imports are from the standard library and which are external imports? Not to me at least, and I don't think that's recommended either. But I think you should structure your code the way you feel makes to most sense to you.– dropbearCommented Mar 9, 2020 at 20:09
-
What do you mean by "
use
works the same as before", before when? Do you meanbefore
as in the other answer?– nbroCommented Jan 1, 2023 at 10:55 -
-
Note that if there is no
editiion = "2018"
(or later) in Cargo.toml, it will default to 2015.– FeeCommented Feb 4 at 16:57
extern crate foo;
? Crates and modules are separate concepts in Rust, you might want to take a look at "Basic terminology: Crates and Modules" which explains the difference between the two (I personally find the examples below overly verbose though).