【Rust】嵌套模块
环境
- Rust 1.56.1
- VSCode 1.61.2
概念
参考:https://doc.rust-lang.org/stable/rust-by-example/mod/visibility.html
示例
模块嵌套
mod my_mod {
pub mod nested {
pub fn function() {
println!("called `my_mod::nested::function()`");
}
}
// 私有模块
mod nested1 {
pub fn function() {
println!("called `my_mod::nested::function()`");
}
}
}
fn main() {
my_mod::nested::function();
// 私有模块不能访问
// my_mod::nested1::function();
}
in crate
mod my_mod {
pub fn function() {
use nested::public_function_in_my_mod;
public_function_in_my_mod();
}
pub mod nested {
// 只能在 create::my_mod 模块中访问
pub(in crate::my_mod) fn public_function_in_my_mod() {
print!("called `my_mod::nested::public_function_in_my_mod()`");
}
}
}
fn main() {
my_mod::function();
}
self
mod my_mod {
pub mod nested {
// `pub(self)` 语法表示只能在当前模块访问和私有一样
pub(self) fn public_function_in_nested() {
println!("called `my_mod::nested::public_function_in_nested()`");
}
}
}
fn main() {
// 编译错误,不能访问
// my_mod::nested::public_function_in_nested();
}
super
mod my_mod {
use self::nested::public_function_in_super_mod;
pub fn function() {
public_function_in_super_mod();
}
pub mod nested {
// 只能在父模块访问
pub(super) fn public_function_in_super_mod() {
println!("called `my_mod::nested::public_function_in_super_mod()`");
}
}
}
fn main() {
my_mod::function();
}
总结
了解了 Rust 中模块的嵌套和各种访问性的问题。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2019-12-07 spring-boot 几个工具类(七)
2019-12-07 spring-boot 连接数据库(六)
2019-12-07 spring-boot 使用 jackson 出错(五)
2019-12-07 spring-boot 使用servlet2.5(四)