rust 初探 -- 路径(path)

rust 初探 -- 路径Path

路径(Path)

  • 目的:为了在 Rust 的模块中找到某个条目,需要使用 路径
  • 两种形式:
    • 绝对路径:从 crate root 开始,使用 crate 名或字面值 crate
    • 相对路径:从当前模块开始,使用 self,super 或当前模块的标识符
  • 路径至少由一个标识符组成,标识符之间使用 ::
    示例:
rust 复制代码
mod front_of_house {
	// pub mod hosting {
    mod hosting {
    	// fn add_to_waitlist() {}
        fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    //使用绝对路径调用
    crate::front_of_house::hosting::add_to_waitlist();
    // --------------- function `add_to_waitlist` is not publicly re-exported
    // 因为是私有的

    //使用相对路径调用
    front_of_house::hosting::add_to_waitlist();
}

私有边界(privacy boundary)

  • 模块不仅可以组织代码,还可以定义私有边界
  • 如果想把函数或struct 等设为私有,将其放到某个模块中即可
  • Rust 中所有的条目默认是私有的
  • 父级模块无法访问子模块中的私有条目
  • 子模块里可以使用所有祖先模块中的条目
pub 关键字
  • 使用 pub 可以将某些条目设置为公共的

super 关键字

  • 用于访问父级模块路径中的内容,相当于文件目录中的 ...
rust 复制代码
fn sever_order() {}

mod back_of_house {
    fn fix_incorrect_order() {
        cook_order();
        super::sever_order();//进入到模块外面
        // crate::sever_order();
    }

    fn cook_order() {}
}

pub struct

  • pub 放在 struct 之前:struct 是公共的,里面的字段默认不是公共的(除非加上 pub)
rust 复制代码
mod back_of_house {
    pub struct Breakfast {
        pub toast: String,
        fruit: String,
    }

    // 关联函数
    impl Breakfast {
        pub fn summer(toast: &str) -> Breakfast {
            Breakfast {
                toast: String::from(toast),
                fruit: String::from("peach"),
            }
        }
    }
}

pub fn eat_at_restaurant() {
    let mut meal = back_of_house::Breakfast::summer("rye");
    meal.toast = String::from("wheat");
    // meal.fruit = String::from("apple");//field `fruit` of `Breakfast` is private
    println!("{}", meal.toast)
}

上述示例中,meal.toast 可以访问,但是meal.fruit 因为是私有的,不能访问。

pub enum

  • 和 struct 不一样,如果枚举是公共的,那么它里面的所有枚举默认就是公共的
相关推荐
qetfw2 小时前
Bash 内置与外部命令:type、command 与 builtin 验证
linux·开发语言·bash
Dovis(誓平步青云)3 小时前
车辆进入隧道后信号断开,座舱旅程怎样补回事件
java·开发语言·前端·数据库·电脑
逆风优雅3 小时前
nestjs middleware 接口请求日志
后端·js
Wzx1980123 小时前
Python Agent 短期记忆设计:从对话历史到 LangGraph Checkpointer
开发语言·python
是枚小菜鸡儿吖3 小时前
听歌截图太普通?我把MusicCard部署到极空间,把歌曲做成随时可开的音乐海报页
服务器·人工智能·后端·ai·大模型
高频因子挖掘机3 小时前
实时行情与分钟 K 线如何协同?Python 量化系统的数据管道设计实践
后端·github·api
gopher95113 小时前
RUST:错误处理 thiserror 详解
开发语言·后端·rust
mldong3 小时前
八种语言的工作流引擎,我用 6 张 UML 图画完了
后端·架构
SkyWalking中文站3 小时前
LLM 回答得好不好?SkyWalking 用 LLM-as-Judge 评估线上回答
后端·aigc