强曰为道
与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

Rust 系统编程语言完全教程 / 第18章:模块系统

第18章:模块系统

18.1 模块基础

内联模块

mod network {
    pub fn connect() {
        println!("连接到网络");
        // 子模块可以访问父模块的私有项
        internal_helper();
    }

    fn internal_helper() {
        println!("内部辅助函数");
    }

    pub mod http {
        pub fn get(url: &str) -> String {
            println!("GET {}", url);
            format!("响应来自 {}", url)
        }
    }
}

fn main() {
    network::connect();
    let response = network::http::get("https://example.com");
    println!("{}", response);
}

文件模块结构

src/
├── main.rs
├── network.rs          // mod network
├── network/            // 或者使用目录形式
│   ├── mod.rs          // mod network 的内容
│   └── http.rs         // mod network::http
└── database.rs         // mod database

18.2 可见性规则

pub 关键字

mod outer {
    pub mod inner {
        pub fn public_fn() {
            println!("公开函数");
            private_fn();
        }

        fn private_fn() {
            println!("私有函数");
        }
    }

    // pub(crate) - 对当前 crate 可见
    pub(crate) fn crate_visible() {
        println!("crate 内可见");
    }

    // pub(super) - 对父模块可见
    pub(super) fn parent_visible() {
        println!("父模块可见");
    }

    // pub(in path) - 指定路径可见
    pub(in crate::outer) fn outer_visible() {
        println!("outer 模块内可见");
    }
}

fn main() {
    outer::inner::public_fn();
    outer::crate_visible();
    // outer::parent_visible(); // ❌ 不可见
    // outer::outer_visible(); // ❌ 不可见(不在 outer 模块内)
}

可见性总结

可见性说明
默认私有,仅当前模块可见
pub公开,所有人可见
pub(crate)当前 crate 内可见
pub(super)父模块可见
pub(in path)指定路径内可见

18.3 use 关键字

基本用法

mod shapes {
    pub mod circle {
        pub fn area(r: f64) -> f64 {
            std::f64::consts::PI * r * r
        }
    }

    pub mod rectangle {
        pub fn area(w: f64, h: f64) -> f64 {
            w * h
        }
    }
}

// 使用 use 引入路径
use shapes::circle;
use shapes::rectangle::area as rect_area;

fn main() {
    println!("圆形面积: {}", circle::area(5.0));
    println!("矩形面积: {}", rect_area(4.0, 6.0));
}

嵌套路径

use std::collections::{HashMap, HashSet, BTreeMap};
use std::io::{self, Read, Write};

fn main() {
    let map: HashMap<&str, i32> = HashMap::new();
    let set: HashSet<i32> = HashSet::new();
    println!("HashMap: {}, HashSet: {}", map.len(), set.len());
}

重导出(Re-export)

mod internal {
    pub struct Config {
        pub host: String,
        pub port: u16,
    }

    impl Config {
        pub fn new() -> Self {
            Self {
                host: "localhost".to_string(),
                port: 8080,
            }
        }
    }
}

// 重导出:外部只需 use crate::Config
pub use internal::Config;

fn main() {
    let config = Config::new();
    println!("{}:{}", config.host, config.port);
}

18.4 模块文件组织

推荐结构

src/
├── main.rs              # 二进制入口
├── lib.rs               # 库入口
├── config.rs            # mod config
├── config/
│   ├── database.rs      # mod config::database
│   └── server.rs        # mod config::server
├── models/
│   ├── mod.rs           # mod models
│   ├── user.rs          # mod models::user
│   └── order.rs         # mod models::order
└── utils/
    ├── mod.rs           # mod utils
    ├── logger.rs        # mod utils::logger
    └── validator.rs     # mod utils::validator

main.rs 示例

// src/main.rs
mod config;
mod models;
mod utils;

use config::Config;
use models::User;

fn main() {
    let config = Config::load();
    let user = User::new("Alice", "[email protected]");
    utils::logger::info(&format!("用户 {} 已创建", user.name));
}

lib.rs 示例

// src/lib.rs
pub mod config;
pub mod models;
pub mod utils;

// 重导出常用类型
pub use config::Config;
pub use models::{User, Order};

18.5 工作空间(Workspace)

Cargo.toml

[workspace]
members = [
    "crates/api",
    "crates/core",
    "crates/cli",
]
resolver = "2"

[workspace.dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

目录结构

project/
├── Cargo.toml           # 工作空间配置
├── Cargo.lock           # 共享锁定文件
├── crates/
│   ├── core/            # 核心库
│   │   ├── Cargo.toml
│   │   └── src/lib.rs
│   ├── api/             # API 服务
│   │   ├── Cargo.toml
│   │   └── src/main.rs
│   └── cli/             # CLI 工具
│       ├── Cargo.toml
│       └── src/main.rs

子 crate Cargo.toml

# crates/api/Cargo.toml
[package]
name = "api-server"
version = "0.1.0"
edition = "2024"

[dependencies]
core = { path = "../core" }
tokio = { workspace = true }
serde = { workspace = true }

18.6 业务场景示例

Web 应用模块结构

web-app/
├── src/
│   ├── main.rs
│   ├── routes/
│   │   ├── mod.rs
│   │   ├── users.rs
│   │   └── orders.rs
│   ├── models/
│   │   ├── mod.rs
│   │   ├── user.rs
│   │   └── order.rs
│   ├── services/
│   │   ├── mod.rs
│   │   ├── auth.rs
│   │   └── email.rs
│   └── middleware/
│       ├── mod.rs
│       └── logging.rs
// src/main.rs
mod routes;
mod models;
mod services;
mod middleware;

pub use models::{User, Order};
pub use services::AuthService;

fn main() {
    println!("Web 应用启动");
}
// src/models/mod.rs
pub mod user;
pub mod order;

pub use user::User;
pub use order::Order;
// src/models/user.rs
#[derive(Debug)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
}

impl User {
    pub fn new(name: &str, email: &str) -> Self {
        Self {
            id: 0,
            name: name.to_string(),
            email: email.to_string(),
        }
    }
}

18.7 本章小结

要点说明
mod声明模块
pub控制可见性
use引入路径
工作空间管理多个相关 crate
模块文件文件/目录自动映射为模块

扩展阅读

  1. Rust Book - 模块 — 官方教程
  2. Cargo 工作空间 — 工作空间详解