渐进性式学习: Rust mod

174 阅读2分钟

关键字

  • 代码组织
  • mod
  • super/crate
  • pub
  • 模块之间相互访问
  • 组织 mod

简单的 mod 使用

main.rs 使用 mod 配合函数使用

mod local {
    pub fn ss() {}
}

fn main() {
    local::ss();
}

模块嵌套使得模块变得复杂

mod local {
    pub mod one {
        pub fn a() {}
        pub fn b() {}
    }

    pub mod two {
        pub fn c() {}
        pub fn d() {}
    } 
}

fn main() {
    local::one::a();
    local::one::b();
    local::two::c();
    local::two::d();
}

mod 拆分到一个文件中, 实现 modmain.rs 分离

// src/single_mod.rs
pub fn single() {
    println!("this is  good");
}

main.rs 中使用 single_mod.rs 模块。

// main.rs
mod single_mod;

fn main() {
    single_mod::single();
}
  1. main.rs 分离,使用 mod 关键与文件名表示模块。
  2. 模块中的公共(pub)方法等使用 :: 路径访问。

同级别模块之间的相互访问

rust 中的同级别的模块之间不能直接的相互访问,但是可以通过父级模块(super)来访问.

// src/main.rs
mod one;
mod two;

fn main() {
    one::hello();
    two::world();
}

use super::two; // 使用 super 访问
use crate::two::world; // 使用 根路径 访问

// src/one.rs
pub fn hello() {
    two::world();
    // world()
}
// src/two.rs
pub fn world() {
    println!("called 2 seconds")
}

one.rs 模块中通过访问 super 关键字来访问 main 中的 two 模块,使用 world 方法被调用了两次。

模块嵌套

模块基本遵循文件/文件夹模式

  • 文件+文件夹模式
  • 文件夹模式

文件 + 文件夹模式

一个文件模块 one.rs (sup-module),表示 one 模块。其次 one 模块下还有很多子模块 sub-module。此时 one 子模块需要写入到 one 文件夹下面。

注意:此时 one 文件夹下面不能有 mod.rs 文件。

// main.rs
mod one;

fn main() {
    one::one_main();
}
// src/one.rs
// one 模块要使用子模块的方法
mod eat;
mod say;

fn one_main() {
    eat::world();
    say::hello();
}
// src/one/eat.rs # eat 模块
pub fn world() {
    println!("eat.rs");
}
// src/one/say.rs # say 模块
pub fn hello() {
    println!("say.rs");
}

文件夹模式

// main.rs
mod one;

fn main() {
    one::one_main();
}

注意: 在文件夹模式下,没有 one.rs 文件,但是要在 one/ 文件夹下面添加 mod.rs 他们之间发生呼唤。并且所有的子模块都需要注册到 mod.rs 目录下。

// src/one/mod.rs
mod eat;
mod say;

fn one_main() {
    eat::world();
    say::hello();
}
// src/one/eat.rs # eat 模块
pub fn world() {
    println!("eat.rs");
}
// src/one/say.rs # say 模块
pub fn hello() {
    println!("say.rs");
}

推荐使用:文件夹模式

小结

  1. Rust 模块化与其他语言模块有些差异
  2. Rust 模块化与文件夹有些类似
  3. Rust 同级模块之间访问,需要通过父模块导入
  4. 推荐使用 文件模式,更容易理解