super:: 父模块路径
什么是 super::
super:: 是 Rust 中的相对路径前缀,指向当前模块的父模块。它类似于文件系统中的 ..,从当前位置向上一级。当子模块需要访问父模块中定义的函数、类型或常量时,就用 super:: 来引用。
rust
mod parent {
pub fn greet() {
println!("来自父模块");
}
mod child {
pub fn call_parent() {
// super:: 指向父模块 parent
super::greet();
}
}
pub fn run() {
child::call_parent();
}
}
fn main() {
parent::run();
}基本用法
rust
mod math {
// 父模块中的常量
pub const PI: f64 = std::f64::consts::PI;
// 父模块中的辅助函数
fn round_to(value: f64, decimals: u32) -> f64 {
let factor = 10_f64.powi(decimals as i32);
(value * factor).round() / factor
}
pub mod circle {
pub fn area(radius: f64) -> f64 {
// 用 super:: 访问父模块的常量和函数
let raw = super::PI * radius * radius;
super::round_to(raw, 4)
}
pub fn perimeter(radius: f64) -> f64 {
let raw = 2.0 * super::PI * radius;
super::round_to(raw, 4)
}
}
pub mod sphere {
pub fn volume(radius: f64) -> f64 {
let raw = (4.0 / 3.0) * super::PI * radius.powi(3);
super::round_to(raw, 4)
}
pub fn surface_area(radius: f64) -> f64 {
let raw = 4.0 * super::PI * radius * radius;
super::round_to(raw, 4)
}
}
}
fn main() {
println!("圆面积(r=5):{}", math::circle::area(5.0));
println!("圆周长(r=5):{}", math::circle::perimeter(5.0));
println!("球体积(r=3):{}", math::sphere::volume(3.0));
println!("球表面积(r=3):{}", math::sphere::surface_area(3.0));
}多层 super
super::super:: 可以向上跳两级,以此类推。不过嵌套太深时用 crate:: 绝对路径更清晰。
rust
mod level1 {
pub fn l1_fn() {
println!("第一层");
}
pub mod level2 {
pub fn l2_fn() {
println!("第二层");
}
pub mod level3 {
pub fn call_all() {
// super:: 回到 level2
super::l2_fn();
// super::super:: 回到 level1
super::super::l1_fn();
// 也可以用 crate:: 绝对路径(更清晰)
crate::level1::l1_fn();
}
}
}
}
fn main() {
level1::level2::level3::call_all();
}super:: 在 use 语句中
rust
mod config {
pub const DB_HOST: &str = "localhost";
pub const DB_PORT: u16 = 5432;
pub const DB_NAME: &str = "myapp";
}
mod database {
// 用 super:: 在 use 中导入兄弟模块的项
use super::config::{DB_HOST, DB_PORT, DB_NAME};
pub fn connection_string() -> String {
format!("postgres://{}:{}/{}", DB_HOST, DB_PORT, DB_NAME)
}
}
mod api {
// 用 super:: 导入兄弟模块
use super::database;
pub fn start() {
let conn = database::connection_string();
println!("API 启动,数据库:{}", conn);
}
}
fn main() {
api::start();
}super:: 访问父模块的私有项
子模块可以通过 super:: 访问父模块的私有项,这是 Rust 可见性规则的一部分。
rust
mod service {
// 私有函数——外部不能访问
fn internal_validate(data: &str) -> bool {
!data.is_empty() && data.len() < 100
}
// 私有常量
const MAX_RETRY: u32 = 3;
pub mod handler {
pub fn process(data: &str) -> Result<String, String> {
// 子模块可以访问父模块的私有项
if !super::internal_validate(data) {
return Err(String::from("数据验证失败"));
}
let mut result = String::new();
for attempt in 1..=super::MAX_RETRY {
result = format!("处理 '{}' 第 {} 次", data, attempt);
}
Ok(result)
}
}
}
fn main() {
// service::internal_validate("test"); // 编译错误:私有函数
match service::handler::process("hello") {
Ok(msg) => println!("成功:{}", msg),
Err(e) => println!("失败:{}", e),
}
}super:: 访问兄弟模块
同级模块之间可以通过 super::兄弟模块名 来互相引用。
rust
mod app {
pub mod models {
pub struct User {
pub name: String,
pub email: String,
}
}
pub mod repository {
use super::models::User;
pub fn find_user(name: &str) -> User {
User {
name: name.to_string(),
email: format!("{}@example.com", name),
}
}
}
pub mod views {
// 通过 super:: 访问兄弟模块
use super::models::User;
use super::repository;
pub fn show_user(name: &str) {
let user = repository::find_user(name);
println!("用户:{}({})", user.name, user.email);
}
}
}
fn main() {
app::views::show_user("张三");
}基本示例
rust
mod game {
// 游戏配置
const BOARD_SIZE: usize = 8;
const INITIAL_LIVES: u32 = 3;
pub struct GameState {
pub score: u32,
pub lives: u32,
pub level: u32,
}
impl GameState {
pub fn new() -> Self {
GameState {
score: 0,
lives: INITIAL_LIVES,
level: 1,
}
}
}
pub mod logic {
use super::GameState;
pub fn add_score(state: &mut GameState, points: u32) {
state.score += points;
// 每 100 分升一级
if state.score / 100 > state.level - 1 {
state.level = state.score / 100 + 1;
println!("升级!当前等级:{}", state.level);
}
}
pub fn lose_life(state: &mut GameState) -> bool {
if state.lives > 0 {
state.lives -= 1;
println!("失去一条命!剩余:{}", state.lives);
true
} else {
println!("游戏结束!");
false
}
}
pub fn board_size() -> usize {
// 访问父模块的私有常量
super::BOARD_SIZE
}
}
pub mod display {
use super::GameState;
pub fn show_status(state: &GameState) {
println!("=== 游戏状态 ===");
println!("分数:{}", state.score);
println!("生命:{}", state.lives);
println!("等级:{}", state.level);
println!("棋盘大小:{}x{}", super::logic::board_size(), super::logic::board_size());
}
}
}
fn main() {
let mut state = game::GameState::new();
game::display::show_status(&state);
game::logic::add_score(&mut state, 50);
game::logic::add_score(&mut state, 60);
game::logic::lose_life(&mut state);
game::display::show_status(&state);
}常见问题
问题一:super:: 能用几层?
语法上可以用任意多层 super::super::super::...,但超过两层就应该考虑用 crate:: 绝对路径了,可读性更好。
问题二:在 crate 根模块中用 super:: 会怎样?
编译错误。crate 根模块没有父模块,super:: 无处可去。
问题三:super:: 和 crate:: 怎么选?
| 场景 | 推荐 | 理由 |
|---|---|---|
| 访问直接父模块的项 | super:: | 简短,关系明确 |
| 访问兄弟模块 | super::兄弟名 | 只跳一级,清晰 |
| 跨越多层模块 | crate:: | 比多个 super 可读性好 |
| 模块可能会被移动 | super:: | 保持相对关系 |
问题四:super:: 和 self:: 可以组合吗?
不能直接组合(如 self::super:: 是非法的)。但可以连用 super::(如 super::super::item)。
适用场景
- 子模块访问父模块:使用父模块定义的常量、类型或函数
- 兄弟模块互相引用:通过
super::兄弟名访问同级模块 - 访问父模块的私有项:子模块有权访问父模块的私有成员
- 模块内部的 use 导入:在
use语句中导入父模块或兄弟模块的项
注意事项
super::指向当前模块的直接父模块- 可以连用多个
super::向上跳多级,但不推荐超过两级 - 在 crate 根模块中使用
super::会编译错误 - 子模块可以通过
super::访问父模块的私有项 - 跨越多层模块时优先考虑
crate::绝对路径 super::在模块重构(整体移动模块位置)时更稳定
总结
super:: 是指向父模块的相对路径前缀,类似文件系统中的 ..。它最常见的用途是子模块访问父模块的项(包括私有项)和兄弟模块之间的互相引用。super:: 可以连用来向上跳多级,但超过两级时用 crate:: 绝对路径可读性更好。super:: 的优势在于保持相对关系——当整个模块子树被移动时,内部使用 super:: 的路径不需要修改。