rust学习——将模块分成不同的文件

随着程序的越来越复杂,我们需要将单文件分割成多文件。
现在创建main.rs文件,其内容如下:

mod front_of_house;

pub use crate::front_of_house::hosting;

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

fn main(){
    eat_at_restaurant()
}

创建front_of_house.rs文件,其内容如下:

pub mod hosting;

创建文件夹src/front_of_house并新添加一个文件hosting.rs,其内容如下:

#![allow(unused_variables)]
pub fn add_to_waitlist() {
    println!("被调用了!!!")
}

运行一下:

D:\learn\cargo_learn>cargo run
   Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
    Finished dev [unoptimized + debuginfo] target(s) in 0.47s
     Running `target\debug\cargo_learn.exe`
被调用了!!!
被调用了!!!
被调用了!!!

D:\learn\cargo_learn>

注意:若想调用一个外部文件暴露出来的模块并将其暴露出去,那么就必须新建一个跟本文件同名称的文件夹,并将外部文件放入此文件夹中,最好模块拆分的很干净能和文件名称保持一致最好

你可能感兴趣的:(rust)