1.相对路径和绝对路径
为了在rust的模块中找到某个条目,需要使用路径
路径的两种形式
- 绝对路径:从crate root开始,使用crate名 或 字面值crate
- 相对路径:从当前模块开始,使用self,super或当前模块的标识符
路径至少由一个标识符组成,多个标识符之间使用 ::
2.私有边界
模块不仅可以组织代码,还可以定义私有边界。
如果想把函数或struct等设为私有,可以将它放到某个模块中
rust中所有的条目(函数,方法,struct,enum,模块,常量),默认都是私有的
父级模块无法访问子模块中的私有条目
子模块中可以使用所有祖先模块中的条目
3. pub关键字
使用 pub关键字 来将某些 条目 标记为公共的
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();
}
front_of_house和eat_at_reataurant都是根级,所以可以相互调用,不用pub
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {
crate::run() // 子集调父级是可以直接调用的
}
}
}
pub fn eat_at_restaurant() {
crate::front_of_house::hosting::add_to_waitlist();
front_of_house::hosting::add_to_waitlist();
}
fn run() {
}
4.super关键字
super关键字来访问父级模块路径中的内容,类似文件系统中的 ..
fn serve_order() {}
mod back_of_house {
fn fix() {
cook();
super::serve_order();
crate::serve_order();
fn niu() {
super::serve_order(); // 这里可以是因为他还在这个模块下
}
}
mod fufu {
// 这里不能使用两个super访问serve_order,只能用crate,因为super只能访问父级模块中的内容
}
fn cook() {}
}
5.pub struct
pub struct 可以把结构体声明为公共的
- struct 是公共的
- struct的字段默认是私有的
在struct中的字段需要单独设置pub来变成公有的
6.pub enum
pub enum 可以把结构体声明为公共的
- enum 是公共的
- enum 的变体也都是公共的