tldr:在 Rust 2018 中,你不需要再写 extern crate 来引入外部依赖。在 Cargo.toml 中设置 edition = "2018" 后,不带 extern crate 的代码也能正常工作。
无需再写 extern crate
你不再需要写 extern crate
来导入一个 crate 到你的项目中了。之前的写法:
extern crate futures;
mod foo {
use futures::Future;
}
之后:
mod foo {
use futures::Future;
}
宏
extern crate 的另一个用途是导入宏,但现在不再需要。在Rust 2015中,您将会写:
#[macro_use]
extern crate log;
fn main() {
error!("oops");
}
现在,您写:
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:
然而,extern crate std
和extern crate core
已经是隐式的了,所以你很少需要手动声明它们。
最后,在nightly中,您将需要它来处理诸如以下crates:
这是唯一的例外。因此,在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
- 除非你正在使用2015版。 - Peter Halluse
而不是extern crate
时,我看到了no wee_alloc external crate
错误。 - Amanda Ferrari