Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between use and extern?

Tags:

rust

People also ask

What does extern Crate do rust?

An extern crate declaration specifies a dependency on an external crate. The external crate is then bound into the declaring scope as the identifier provided in the extern crate declaration.

What is extern rust?

The extern keyword is used in two places in Rust. One is in conjunction with the crate keyword to make your Rust code aware of other Rust crates in your project, i.e., extern crate lazy_static; . The other use is in foreign function interfaces (FFI). extern is used in two different contexts within FFI.

What is use crate rust?

Keyword crate A Rust binary or library. The primary use of the crate keyword is as a part of extern crate declarations, which are used to specify a dependency on a crate external to the one it's declared in. Crates are the fundamental compilation unit of Rust code, and can be seen as libraries or projects.


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.


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.