22_路径

1. 概述

在rust里,如果我们想要找到某个模块,我们必须知道其路径,rust的路径有两种形式。

绝对路径:从crate root开始,使用 crate 名或字面值 crate。相对路径:从当前模块开始,使用self、super,或者当前模块的标识符。不管是绝对路径还是相对路径,只有由一个标识符组成,如果存在多个标识符,标识符之间使用::进行分割。

示例代码如下src/lib.rs

rust 复制代码
mod front_of_house {
    mod hosting {
        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_restaurant函数在同一个级别,所以函数里可以直接调用。不过上面的代码看似没有问题,但当我们编译的时候会报错。我们将在下文解决这个问题。

2. 私有边界(privacy boundary)

模块不仅可以组织代码,还可以定义私有边界。如果想把函数或者struct等设置为私有,就可以将它放到某个模块中。Rust中所有条目(函数、方法、struct、enum、模块、常量)默认是私有的。父级模块无法访问子级模块中的私有条目,在子模块里,可以使用所有祖先模块的条目。

2.1 pub关键字

使用pub关键字可以将某些条目标记为公共的。我们将"一"中的代码改为如下,将不会再出现错误

rust 复制代码
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之所以不需要添加pub关键字,因为front_of_houseeat_at_restaurant都在文件根级,可以互相调用。

2.2 super关键字

super关键字用来访问父级模块中的内容,类型文件系统中的..。如下示例代码

rust 复制代码
fn serve_order() {}

mod back_of_house {
    fn fix_incorrect_order() {
        cook_order();
        // 使用相对路径的方式调用
        super::serve_order();
        // 使用绝对路径的方式调用
        crate::serve_order();
    }

    fn cook_order() {}
}

2.3 pub struct

pub 放在struct 之前,代表公共的结构体,struct 里面的字段默认是私有的,想把哪个字段设置为公有,就在对应的字段前面加上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("peachers"),
            }
        }
    }
}

pub fn eat_at_restaurant() {
    let mut meal = back_of_house::Breakfast::summer("Rye");
    meal.toast = String::from("Wheat");
    println!("I'd like {} toast please", meal.toast);
}

2.4 pub enum

pub 放在 enum 前面是将enum声明为公共。枚举中的变体都变成公共的。如下示例代码

rust 复制代码
mod back_of_house {
    pub enum Appetizer {
        Soup,
        Salad,
    }
}
相关推荐
ftpeak14 小时前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
咸甜适中15 小时前
rust语言 (1.88) 学习笔记:客户端和服务器端同在一个项目中
笔记·学习·rust
人工智能训练师15 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny0715 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy16 小时前
css的基本知识
前端·css
昔人'16 小时前
css `lh`单位
前端·css
Nan_Shu_61418 小时前
Web前端面试题(2)
前端
知识分享小能手18 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队19 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光19 小时前
css之一个元素可以同时应用多个动画效果
前端·css