为什么有时需要使用extern crate?

25

我想知道为什么有时我们需要使用 extern crate 而不是 use?我正在使用 wee_alloc 的 crate,要导入它的模块,我必须使用 extern crate

extern crate wee_alloc;

// Use `wee_alloc` as the global allocator.
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

但是使用 web_sys,我只需使用 use


1
你不需要使用 extern crate - 除非你正在使用2015版。 - Peter Hall
我正在使用最新版本的 Rust,当我使用 use 而不是 extern crate 时,我看到了 no wee_alloc external crate 错误。 - Amanda Ferrari
你能提供完整的错误信息吗? - Ibraheem Ahmed
在2021年,没有必要使用它。 - Tomasz Waszczyk
1个回答

47

tldr:在 Rust 2018 中,你不需要再写 extern crate 来引入外部依赖。在 Cargo.toml 中设置 edition = "2018" 后,不带 extern crate 的代码也能正常工作。

无需再写 extern crate

你不再需要写 extern crate 来导入一个 crate 到你的项目中了。之前的写法:

// Rust 2015

extern crate futures;

mod foo {
    use futures::Future;
}

之后:

// Rust 2018

mod foo {
    use futures::Future;
}

extern crate 的另一个用途是导入宏,但现在不再需要。在Rust 2015中,您将会写:

// Rust 2015

#[macro_use]
extern crate log;

fn main() {
    error!("oops");
}

现在,您写:

// Rust 2018

use log::error;

fn main() {
    error!("oops");
}

重命名 crates

如果你一直在使用as来重命名你的 crate,像这样:

extern crate futures as fut;

然后在Rust 2018中,你只需要这样做:

use futures as fut;

use fut::Future;

Sysroot Crates

有一个例外,那就是“sysroot” crates。这些是Rust本身分发的crates。目前为止,您仍然需要使用extern crate来获取这些crates:

  • proc_macro
  • core
  • std

然而,extern crate stdextern crate core已经是隐式的了,所以你很少需要手动声明它们。

最后,在nightly中,您将需要它来处理诸如以下crates:

  • alloc
  • test

这是唯一的例外。因此,在Rust 2018中,您提供的没有extern crate的代码完全可以正常工作:

#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

设置 Rust 版本

仅仅安装了最新的 Rust 版本并不意味着你正在使用最新的版本。要告诉 Cargo 使用特定的版本,请设置 edition 键值对。例如:

[package]
name = "foo"
edition = "2018"
如果没有edition键,Cargo将默认使用Rust 2015。但在这种情况下,我们选择了2018年版,因此我们的代码正在使用Rust 2018进行编译!感谢@KevinReid指出这一点。
本答案来源于Rust Edition Guide

这部分回答了我的问题。我仍然需要使用 extern crate wee_alloc,否则在编译时会弹出错误:no wee_alloc external crate - Amanda Ferrari
你无法运行我回答末尾的代码吗?你使用的是哪个版本的Rust? - Ibraheem Ahmed
1
这个回答没有提到您需要在Cargo.toml指定版本——否则它会默认为“'2015'”以保持向后兼容性。 - Kevin Reid
2
我认为缺失的区别是,安装了最新版本的 Rust 并不意味着所选择的语言版本是最新的。 - Kevin Reid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接