Rust中的crate和mod
Xhofe Lv3

crate

先看看官方的定义:

A crate is a binary or library. The crate root is a source file that the Rust compiler starts from and makes up the root module of your crate (we’ll explain modules in depth in the “Defining Modules to Control Scope and Privacy” section). A package is one or more crates that provide a set of functionality. A package contains a Cargo.toml file that describes how to build those crates.

crate是rust中的最小编译单元,也就是说rust是按照一个一个的crate来编译的,每个crate都有一个入口文件,可以是下面三种情况:

  • src下的main.rs文件
  • src下的lib.rs文件(作为一个库)
  • src/bin目录下的任意文件(包含main函数)

mod

而mod则更像是C++中的命名空间,以下几种情况都可以作为一个根mod:

  • 一个单独的文件为一个mod
  • 一个文件夹中包含mod.rs(其他的文件在mod.rs中被声明成子mod)
  • 文件夹同级的同名rs文件

mod是可以嵌套的,它是一个树形结构,要想使用mod,则必须在某个入口文件中声明mod(其实rust就是以这个mod名称寻找文件进行了替换),而子mod则可以在它的父mod中进行声明,然后在要使用的地方有以下几种使用方式:

  • 在本文件中声明了mod,则可以直接使用这个mod;
  • 使用use关键字引入在其他文件中声明的mod;
  • 在src/bin目录下要使用同crate下的mod,则需要:在lib.rs中进行声明,然后使用这个crate的名称作为路径来use;
  • 在src/main.rs 可以使用上一种方式,但也可以去掉lib.rs而直接在本文件中来声明mod;
  • 所有的声明mod在其他文件中被use的话都需要pub导出;
  • use只是为了简化路径,也可以直接从根mod一直写下去而不使用use关键字。

示例

文件:

1
2
3
4
5
6
7
8
9
10
├─src
│ │ lib.rs
│ │ main.rs
│ │
│ ├─bin
│ │ test.rs
│ │
│ └─test_mod
│ child.rs
│ mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// test_mod/child.rs
pub fn test(){
println!("hello,world")
}
// test_mod/mod.rs
pub mod child; // 导出子mod
// lib.rs
pub mod test_mod; // 将本crate声明为一个库
// main.rs
mod test_mod;
fn main() {
test_mod::child::test();
}
// 或者直接:
fn main() {
crate_mod::test_mod::child::test()
}
// bin/test.rs
use crate_mod::test_mod::child;
fn main() {
child::test()
}
  • 本文标题:Rust中的crate和mod
  • 本文作者:Xhofe
  • 创建时间:2022-02-17 14:08:00
  • 本文链接:https://nn.ci/posts/rust-crate-mod.html
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论