Extern crate 声明
语法
ExternCrate :
externcrateCrateRef AsClause?;CrateRef :
标识符 |selfAsClause :
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 crate 时,不允许使用连字符。然而,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 依赖,而无需在作用域中绑定其名称。这对于只需要链接但从不引用的 crate 可能很有用,并且可以避免被报告为未使用。
macro_use 属性按通常方式工作,并将宏名称导入到 macro_use prelude 中。
no_link 属性
no_link 属性可以在 extern crate 项上指定,以防止将该 crate 链接到输出中。这通常用于加载 crate 以仅访问其宏。