当前位置: 首页 > 文档资料 > 通过例子学 Rust >

crate - extern crate

优质
小牛编辑
116浏览
2023-12-01

链接一个 crate 到这个新库,必须使用 extern crate 声明。这不仅会链接库,还会导入与库名相同的模块里面的所有项。适用于模块的可见性规则也适用于库。

  1. // 链接到 `library`(库),导入 `rary` 模块里面的项
  2. extern crate rary;
  3. fn main() {
  4. rary::public_function();
  5. // 报错! `private_function` 是私有的
  6. //rary::private_function();
  7. rary::indirect_access();
  8. }
  1. # library.rlib 是已编译好的库的路径,假设在这里它在同一目录下:
  2. # (原文:Where library.rlib is the path to to the compiled library,
  3. # assumed that it's in the same directory here:)
  4. $ rustc executable.rs --extern rary=library.rlib && ./executable
  5. called rary's `public_function()`
  6. called rary's `indirect_access()`, that
  7. > called rary's `private_function()`