What's the difference between use and extern?

Rust

Rust Problem Overview


I'm new to Rust. I think that use is used to import identifiers into the current scope and extern 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?

Rust Solutions


Solution 1 - Rust

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.

Solution 2 - Rust

The accepted answer was correct at the time of writing. It's however no longer correct. extern crate is almost never needed since Rust 2018.

You're now only required to add external dependencies to your Cargo.toml.

use works the same as before.

Read more in the official documentation.

Edit: The accepted answer has now been edited to correctly reflect the changes in Rust 2018.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarallaView Question on Stackoverflow
Solution 1 - RustShepmasterView Answer on Stackoverflow
Solution 2 - RustdropbearView Answer on Stackoverflow