简体   繁体   English

use 和 extern 有什么区别?

[英]What's the difference between use and extern?

I'm new to Rust.我是 Rust 的新手。 I think that use is used to import identifiers into the current scope and extern is used to declare an external module.我认为use用于将标识符导入当前范围,而extern用于声明外部模块。 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 有这两个概念以及使用它们的合适情况是什么?

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 ). extern crate foo表示您要链接外部库并将顶级 crate 名称带入范围(相当于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.从 Rust 2018 开始,在大多数情况下, 您将不再需要使用extern crate因为 Cargo 会通知编译器存在哪些 crate。 (There are one or two exceptions ) (有一两个例外

use bar is a shorthand for referencing fully-qualified symbols. use bar是引用完全限定符号的简写。

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!理论上,该语言不需要use ——您总是可以完全限定名称,但是键入std::collections::HashMap.new(...)会变得非常乏味! Instead, you can just type use std::collections::HashMap once and then HashMap will refer to that.相反,您只需键入use std::collections::HashMap一次,然后HashMap将引用它。

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.自 Rust 2018 以来几乎不再需要extern crate

You're now only required to add external dependencies to your Cargo.toml.您现在只需要向 Cargo.toml 添加外部依赖项。

use works the same as before. use和以前一样。

Read more in the official documentation .官方文档中阅读更多内容

Edit: The accepted answer has now been edited to correctly reflect the changes in Rust 2018.编辑:已接受的答案现已被编辑,以正确反映 Rust 2018 中的变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM