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

如何在Rust中实现仅对指定子模块可见的方法(类似Java包私有)

Rust中实现类似Java包私有的可见性控制

项目结构

/src
  /stuff
    /mod.rs
    /foo.rs
  /stuff2
    /mod.rs
    /foo2.rs

各mod.rs内容:

  • stuff/mod.rs:pub mod foo;
  • stuff2/mod.rs:pub mod foo2;

现有foo.rs代码

pub struct Foo {}

impl Foo {
  fn private_method() {}
  pub fn public_method() {}
  pub fn visible_only_within_stuff_method() {}
}

解决方案

要让visible_only_within_stuff_method()仅对/stuff目录下的代码可见,你可以使用Rust的路径限定可见性修饰符,具体修改如下:

修改foo.rs中的方法定义:

pub struct Foo {}

impl Foo {
  fn private_method() {}
  pub fn public_method() {}
  // 限定该方法仅在`crate::stuff`模块及其子模块内可见
  pub(in crate::stuff) fn visible_only_within_stuff_method() {}
}

效果说明

  • 在stuff目录下的任意模块(比如新增stuff/bar.rs)中,你可以正常调用Foo::visible_only_within_stuff_method()
  • 在stuff2目录或者项目根模块等stuff外部的代码中,尝试调用该方法会触发编译器错误,提示方法不可见

补充说明

  • 如果你在foo.rs中,也可以用pub(in self::..)替代pub(in crate::stuff),效果完全一致(self::..表示当前模块的父模块,也就是crate::stuff)
  • 避免使用pub(crate),它会让方法对整个crate可见,范围超出了你需要的stuff目录限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:03:21