模块基础 #

一、模块定义 #

1.1 mod 关键字 #

rust
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {
            println!("添加到等待列表");
        }
    }
}

fn main() {
    front_of_house::hosting::add_to_waitlist();
}

1.2 文件模块 #

text
src/
├── main.rs
└── front_of_house/
    ├── mod.rs
    └── hosting.rs
rust
// src/main.rs
mod front_of_house;

fn main() {
    front_of_house::hosting::add_to_waitlist();
}
rust
// src/front_of_house/mod.rs
pub mod hosting;
rust
// src/front_of_house/hosting.rs
pub fn add_to_waitlist() {
    println!("添加到等待列表");
}

二、可见性 #

2.1 pub 关键字 #

rust
mod back_of_house {
    pub struct Breakfast {
        pub toast: String,
        seasonal_fruit: String,
    }
    
    impl Breakfast {
        pub fn summer(toast: &str) -> Breakfast {
            Breakfast {
                toast: String::from(toast),
                seasonal_fruit: String::from("peaches"),
            }
        }
    }
}

fn main() {
    let mut meal = back_of_house::Breakfast::summer("Rye");
    meal.toast = String::from("Wheat");
    // meal.seasonal_fruit = String::from("blueberries");  // 错误:私有字段
}

2.2 可见性修饰符 #

修饰符 说明
pub 公开
pub(crate) crate内可见
pub(super) 父模块可见
pub(in path) 指定路径可见

三、use 导入 #

3.1 基本用法 #

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

use front_of_house::hosting;

fn main() {
    hosting::add_to_waitlist();
}

3.2 as 别名 #

rust
use std::io::Result as IoResult;

3.3 嵌套路径 #

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

3.4 glob 导入 #

rust
use std::collections::*;

四、总结 #

本章学习了:

  • 模块定义
  • 可见性控制
  • use 导入

下一章,我们将学习包与Crate。

最后更新:2026-03-27