包龙星

来人啊!把犯人带到后堂审问!

方唐镜

且慢!后堂是私密区域 (private),闲杂人等不得入内。除非大人您显式地允许 (pub)。

豹子头 (雷豹)

我不管!我要全都要!(use *)

Rust 组织管理:衙门的规矩

Rust 提供了一套强大的模块系统来组织代码,包括:Packages(包)、Crates(箱)、Modules(模块)和 Paths(路径)。

🏛️ 模块定义 (mod)

使用 mod 关键字定义模块。默认情况下,模块内的东西都是私有的。

mod yamen {
    // 默认是私有的,外面访问不到
    fn torture() {
        println!("上大刑!");
    }

    // pub 关键字使其公开
    pub fn open_court() {
        println!("升堂!");
        // 内部可以访问私有函数
        torture(); 
    }
}

fn main() {
    yamen::open_court(); // ✅ 可以访问
    // yamen::torture(); // ❌ 报错!私有函数
}

📂 父子模块与路径

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // 绝对路径
    crate::front_of_house::hosting::add_to_waitlist();

    // 相对路径
    front_of_house::hosting::add_to_waitlist();
}

🚚 use 关键字

使用 use 将路径引入作用域,就不用每次都写全名了。

use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
}

📄 分割到不同文件

当模块变大时,应该把它们移动到单独的文件中。

src/lib.rs:

mod front_of_house; // 声明模块,内容在 front_of_house.rs 中寻找
🏘️

动手时刻:重组衙门

编写一个简单的模块结构。

  1. 定义一个模块 court (公堂)。
  2. court 里定义一个公开函数 judge (判案)。
  3. court 里定义一个私有函数 bribe (行贿)。
  4. 尝试在 main 函数里调用 judge
  5. 尝试在 main 函数里调用 bribe,观察报错。
查看参考答案 (点击揭榜)

mod court {
    pub fn judge() {
        println!("本官宣判:你有罪!");
    }

    fn bribe() {
        println!("嘘...这是五千两...");
    }
}

fn main() {
    court::judge();
    // court::bribe(); // Error: function `bribe` is private
}
                    

成就解锁:【衙门提督】 🏛️