Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

外部 crate 声明

Syntax
ExternCrateextern crate CrateRef AsClause? ;

CrateRefIDENTIFIER | self

AsClauseas ( IDENTIFIER | _ )

_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 crate 时,不允许使用连字符。但是,Cargo 包可以使用它们。在这种情况下,当 Cargo.toml 未指定 crate 名称时,Cargo 会透明地将 - 替换为 _(有关更多详细信息,请参阅 RFC 940)。

这是一个示例:

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

下划线导入

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

macro_use 属性照常工作,并将宏名称导入到 macro_use prelude中。

no_link 属性 可以应用于 extern crate 项以阻止链接该 crate。

Note

这很有用,例如,当只需要 crate 的宏时。

Example

#[no_link]
extern crate other_crate;

other_crate::some_macro!();

no_link 属性使用 MetaWord 语法。

no_link 属性只能应用于 extern crate 声明。

Note

rustc 会忽略在其他位置的使用,但会发出 lint 警告。这可能在未来成为错误。

只有 extern crate 声明上的第一次使用 no_link 才有效果。

Note

rustc 会对第一次之后的任何使用发出 lint 警告。这可能在未来成为错误。