205

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?

1
  • 13
    Are you referring to the statement 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). Commented Apr 2, 2015 at 2:34

2 Answers 2

209

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.

1
  • 10
    Without use, we couldn't even have std as the facade it is. Either we'd have a single monolithic standard library crate, or everyone would be dealing with the fact that String is actually collections::string::String.
    – user395760
    Commented Apr 2, 2015 at 11:11
132

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.

5
  • 2
    Even if it's not necessary, isn't there a benefit in separating external crates from standard ones? Like extern crate failure; but use 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.
    – dropbear
    Commented Mar 9, 2020 at 20:09
  • What do you mean by "use works the same as before", before when? Do you mean before as in the other answer?
    – nbro
    Commented Jan 1, 2023 at 10:55
  • @nbro I mean as in before Rust 2018.
    – dropbear
    Commented Jan 3, 2023 at 10:25
  • Note that if there is no editiion = "2018" (or later) in Cargo.toml, it will default to 2015.
    – Fee
    Commented Feb 4 at 16:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.