self:: 相对路径 ​

什么是 self:: ​

self:: 表示当前模块自身,是一种相对路径的写法。用 self:: 前缀来引用当前模块中定义的项。在大多数情况下 self:: 可以省略,但在某些场景下它能消除歧义或让代码意图更明确。

rust
mod utils {
    pub fn helper() {
        println!("辅助函数");
    }

    pub fn run() {
        // self:: 指向当前模块(utils)
        self::helper();  // 等价于直接写 helper()
        helper();        // 省略 self:: 也可以
    }
}

fn main() {
    utils::run();
}

self:: 在 use 语句中的作用 ​

self:: 在 use 语句中最常见,特别是在导入当前模块的子模块或兄弟项时。

rust
mod network {
    pub mod http {
        pub fn get() -> String {
            String::from("HTTP GET")
        }

        pub fn post() -> String {
            String::from("HTTP POST")
        }
    }

    pub mod tcp {
        pub fn connect() -> String {
            String::from("TCP 连接")
        }
    }

    // 在 use 中用 self:: 导入当前模块的子模块
    pub fn init() {
        use self::http::get;
        use self::tcp::connect;

        println!("{}", get());
        println!("{}", connect());
    }
}

fn main() {
    network::init();
}

self 在嵌套导入中的使用 ​

use 语句支持嵌套导入(也叫树状导入),self 在这里表示"模块本身"。

rust
mod io {
    pub fn read() {
        println!("读取数据");
    }

    pub fn write() {
        println!("写入数据");
    }

    pub mod buffer {
        pub fn flush() {
            println!("刷新缓冲区");
        }
    }
}

// 嵌套导入:self 表示 io 模块本身的项
use io::{self, buffer};
// 等价于:
// use io;
// use io::buffer;

fn main() {
    io::read();
    io::write();
    buffer::flush();
}

这种写法在标准库导入中很常见:

rust
// 同时导入 std::io 模块和它里面的 Write trait
use std::io::{self, Write};

fn main() {
    // io 指向 std::io 模块
    let stdout = io::stdout();
    let mut handle = stdout.lock();

    // Write 是从 std::io::Write 导入的
    handle.write_all(b"Hello\n").unwrap();
}

self:: 消除歧义 ​

当当前模块中的项和导入的外部项同名时,self:: 可以明确指定使用当前模块的项。

rust
mod formatter {
    // 当前模块有一个 format 函数
    pub fn format(data: &str) -> String {
        format!("[格式化] {}", data)
    }

    pub mod html {
        pub fn render(content: &str) -> String {
            // 这里想调用父模块的 format,不是标准库的 format! 宏
            // 用 super:: 指明是父模块的函数
            let formatted = super::format(content);
            format!("<div>{}</div>", formatted)
        }
    }
}

fn main() {
    let result = formatter::html::render("Hello");
    println!("{}", result);
}

self:: vs 其他路径前缀 ​

前缀含义起点
self::当前模块当前模块
super::父模块上一级模块
crate::crate 根main.rs / lib.rs
无前缀当前模块(隐含 self::)当前模块
rust
mod parent {
    pub fn parent_fn() {
        println!("来自 parent");
    }

    pub mod child {
        pub fn demo() {
            // self:: 当前模块
            self::local_fn();

            // super:: 父模块
            super::parent_fn();

            // crate:: 从根开始
            crate::parent::parent_fn();
        }

        fn local_fn() {
            println!("来自 child");
        }
    }
}

fn main() {
    parent::child::demo();
}

基本示例 ​

rust
mod math {
    pub const PI: f64 = std::f64::consts::PI;

    pub fn circle_area(radius: f64) -> f64 {
        self::PI * radius * radius
    }

    pub fn circle_perimeter(radius: f64) -> f64 {
        2.0 * self::PI * radius
    }

    pub mod geometry {
        // 导入当前模块的父模块的项
        use super::{circle_area, circle_perimeter};

        pub fn circle_info(radius: f64) -> String {
            let area = circle_area(radius);
            let perimeter = circle_perimeter(radius);
            format!("半径={:.1}, 面积={:.2}, 周长={:.2}", radius, area, perimeter)
        }
    }

    pub mod trigonometry {
        pub fn sin_deg(degrees: f64) -> f64 {
            // 用 super:: 访问父模块的常量
            let radians = degrees * super::PI / 180.0;
            radians.sin()
        }

        pub fn cos_deg(degrees: f64) -> f64 {
            let radians = degrees * super::PI / 180.0;
            radians.cos()
        }
    }
}

fn main() {
    println!("{}", math::geometry::circle_info(5.0));
    println!("sin(30°) = {:.4}", math::trigonometry::sin_deg(30.0));
    println!("cos(60°) = {:.4}", math::trigonometry::cos_deg(60.0));
}

常见问题 ​

问题一:self:: 可以省略吗?

在函数调用和直接引用中可以省略——self::foo() 和 foo() 效果一样。但在 use 的嵌套导入中不能省略,use module::{self, item} 中的 self 是必须的。

问题二:self 和 Self 有什么区别?

完全不同的东西。小写 self 是模块路径前缀(也是方法中的实例参数);大写 Self 是类型别名,指向当前 impl 块的类型。

rust
struct Point { x: f64, y: f64 }

impl Point {
    // Self 指向 Point 类型
    fn new(x: f64, y: f64) -> Self {
        Self { x, y }
    }

    // self 是实例参数(&self 表示不可变引用)
    fn distance(&self) -> f64 {
        (self.x * self.x + self.y * self.y).sqrt()
    }
}

fn main() {
    let p = Point::new(3.0, 4.0);
    println!("距离:{}", p.distance());
}

问题三:use self:: 和 use super:: 有什么区别?

use self::xxx 从当前模块导入,use super::xxx 从父模块导入。在同一个模块中,self:: 通常可以省略;但跨模块时 super:: 不能省略。

适用场景 ​

  • use 嵌套导入:use module::{self, item} 同时导入模块和它的项
  • 消除歧义:当前模块的项和外部项同名时
  • 明确意图:让代码阅读者知道这个项来自当前模块
  • 宏中的路径:宏展开时 self:: 可以确保引用正确的模块

注意事项 ​

  • self:: 在大多数场景下可以省略
  • use module::{self, item} 中的 self 不能省略
  • self 和 Self 是完全不同的概念
  • self:: 不能跨模块使用,只指向当前模块
  • 在 use 语句中,self 代表被导入的模块本身

总结 ​

self:: 是指向当前模块的相对路径前缀。在大多数直接调用中可以省略,但在 use 语句的嵌套导入中是必要的——use module::{self, item} 这种写法可以同时导入模块本身和它的子项。self:: 还可以在存在命名冲突时消除歧义。和 super::(父模块)、crate::(根模块)一起,这三个前缀构成了 Rust 模块路径系统的完整导航工具。