You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通配符导入后self为何指向testing::nested而非main模块?

Rust通配符导入后self路径解析疑问解析

问题代码

// main.rs
use testing::nested::*;

fn main() {
    self::hello();
}

// lib.rs (testing module)
pub mod nested {
    pub fn hello() { // 补充缺失的`fn`关键字,否则无法编译
        println!("hello from nested::hello");
    }
}

疑问

为何执行通配符导入use testing::nested::*后,调用self::hello()会执行testing::nested::hello,仿佛self指向了testing::nested而非main二进制模块?烦请告知相关官方文档的位置。

解析

核心逻辑:通配符导入的项会并入当前模块作用域

你这里的误解并非self指向了testing::nested,而是**use testing::nested::*将nested模块的所有公开项直接导入到了main模块的顶层作用域**:

  • self::在路径中始终指代当前代码所在的模块(这里就是main模块)。
  • 导入后的hello函数相当于“挂靠”在main模块下,所以self::hello()实际是调用main模块作用域内的hello——也就是从nested导入的那个函数。

可以通过以下代码验证这一点:

// main.rs
use testing::nested::*;

// 在main模块定义同名函数
fn hello() {
    println!("hello from main module");
}

fn main() {
    self::hello(); // 会打印"hello from main module",证明self仍指向main模块
}

官方文档参考

Rust官方文档的**「模块与路径」章节**中,关于「使用use导入名称」的部分明确说明:

  • 通配符*会将目标模块的所有公开项导入到当前作用域,这些导入项与当前模块内定义的项处于同一名称空间。
  • 路径解析时,self::会优先查找当前模块作用域内的项(包括导入的项)。

内容的提问来源于stack exchange,提问作者Gaston Sanchez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 20:10:28