使用和外部有什么区别?

What's the difference between use and extern?

我是 Rust 新手。我认为 use 用于将标识符导入当前范围,而 extern 用于声明外部模块。但是这种理解(也许是错误的)对我来说没有任何意义。谁能解释一下为什么 Rust 有这两个概念,以及在什么情况下适合使用它们?

extern crate foo 表示你想 link 针对外部库并将顶级 crate 名称引入范围(相当于 use foo)。从 Rust 2018 开始,在大多数情况下 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 是一个 shorthand 用于引用完全限定的符号。

理论上,该语言 不需要 use — 您总是可以完全限定名称,但键入 std::collections::HashMap.new(...) 会变得非常乏味!相反,您只需键入 use std::collections::HashMap 一次,然后 HashMap 将引用它。

在撰写本文时,接受的答案是正确的。然而,它不再正确。 extern crate 自 Rust 2018 以来几乎不再需要。

您现在只需要将外部依赖项添加到您的 Cargo.toml。

use 和以前一样工作。

official documentation 阅读更多内容。

编辑:已接受的答案现已被编辑以正确反映 Rust 2018 中的更改。