RUST学习-代码组织形式package、crate、mod

rust代码组织分为package、crate、mod

rust代码出于安全性考虑声明的函数、mod、默认都是私有的,如果想导出需要在他们前面加上关键字“pub”

在别的文件如果想引用mod或者函数需要使用use关键字

mod声明和内容独立成文件

mod独立成文件,需要按照crate树结构创建同名的mo文件

1.在lib.rs里声明mod front_of_hosting;注意这里是;
2.按照crate树状结构创建同名的.rs文件这里是front_of_hosting.rs
3.如果mod存在嵌套子mod的情况,比如这里front_of_hosting嵌套了serving和hosting,则在父mod的rs文件同样声明子mod,这里是mod hosting;和mod serving;注意这里是;
4.创建父mod文件夹,这里是front_of_hosting文件夹,在父mod文件夹里创建子mod的同名.rs文件\
5.在同名的mod的rs文件中编写代码

lib.rs 声明父类mod

1
pub mod front_of_hosting;

front_of_hosting.rs,这里声明了俩个子mod

1
2
3
pub mod hosting;

pub mod serving;

front_of_hosting\hosting.rs 实现mod hosting

1
2
3
4
5
6
7
pub fn add_to_waitlist() {
println!("add_to_waitlist");
}

pub fn seat_at_table() {
println!("seat_at_table");
}

front_of_hosting\serving.rs 实现mod rust

1
2
3
4
5
pub fn take_order() {}

fn server_order() {}

fn take_payment() {}

pub use

默认的use是私有的,在别的文件是无法使用这个use的,如果想使用需要在use前面也加上关键字,

一般pub use多用于重导出的场景,即:re-export

比如我们又一个mod的路径是 crate::my_project::front_of_hosting::hosting,我们在使用他的地方都需要“use my_project::front_of_hosting::hosting”,有没有简单的导出方法呢,是有的见下面

  • 因为 lib.rs里有pub use front_of_hosting::hosting
  • 所以main.rs里能直接 my_project::hosting,省略掉路径front_of_hosting而直接导出了hosting
  • 也可以写相对路径my_project::front_of_hosting::hosting
  • 也可以re-export函数,即在lib.rs pub use front_of_hosting::serveing::take_order,这里可以直接调用my_project::take_order

lib.rs

1
2
3
pub mod front_of_hosting;

pub use front_of_hosting::hosting;

main.rs
见这里use my_project::front_of_hosting::hosting 和 use my_project::hosting as pub_hosting;【为了避免重名起了个别名】

1
2
3
4
5
6
7
8
9
use my_project::front_of_hosting::hosting;
use my_project::hosting as pub_hosting;


fn main() {

pub_hosting::add_to_waitlist();
hosting::add_to_waitlist();
}