外部 crate 声明

语法:
ExternCrate :
   extern crate CrateRef AsClause? ;

CrateRef :
   标识符 | self

AsClause :
   as ( 标识符 | _ )

一个 extern crate 声明 指定对外部 crate 的依赖。

然后,外部 crate 以给定的 标识符 的形式绑定到声明作用域中的 类型命名空间 中。

此外,如果 extern crate 出现在 crate 根目录中,则 crate 名称也会被添加到 外部 prelude 中,使其在所有模块中自动处于作用域内。

as 子句可用于将导入的 crate 绑定到不同的名称。

外部 crate 在编译时被解析为特定的 soname,并且将对该 soname 的运行时链接需求传递给链接器,以便在运行时加载。soname 在编译时通过扫描编译器的库路径并匹配提供的可选 crate_name 与在编译外部 crate 时声明的 crate_name 属性 来解析。如果未提供 crate_name,则假定默认的 name 属性,该属性等于在 extern crate 声明中给定的 标识符

可以导入 self crate,它会创建到当前 crate 的绑定。在这种情况下,必须使用 as 子句来指定要绑定到的名称。

以下是 extern crate 声明的三个示例

extern crate pcre;

extern crate std; // equivalent to: extern crate std as std;

extern crate std as ruststd; // linking to 'std' under another name

在命名 Rust crates 时,不允许使用连字符。但是,Cargo 包可能会使用它们。在这种情况下,如果 Cargo.toml 没有指定 crate 名称,Cargo 将透明地将 - 替换为 _ (有关更多详细信息,请参阅 RFC 940)。

这是一个例子

// Importing the Cargo package hello-world
extern crate hello_world; // hyphen replaced with an underscore

下划线导入

可以通过使用带有 extern crate foo as _ 形式的下划线来声明外部 crate 依赖关系,而无需将其名称绑定到作用域中。这对于只需要链接而从不引用的 crates 可能会有用,并且可以避免被报告为未使用。

macro_use 属性 像往常一样工作,并将宏名称导入到 macro_use prelude 中。

可以在 extern crate 项上指定 no_link 属性,以防止将 crate 链接到输出中。这通常用于加载 crate 以仅访问其宏。