pub use 重导出 ​

什么是 pub use ​

pub use 把另一个模块中的项导入到当前模块,并同时将其公开——外部代码可以通过当前模块的路径来访问这个项,就好像它是在当前模块中定义的一样。这种机制叫做"重导出"(Re-export),是 Rust 库设计中非常重要的工具。

rust
mod internal {
    pub fn helper() {
        println!("来自 internal 模块的函数");
    }

    pub struct Config {
        pub name: String,
    }
}

// pub use 把 internal 的项重导出到当前模块
pub use internal::helper;
pub use internal::Config;

fn main() {
    // 可以直接用,不需要知道 internal 模块的存在
    helper();
    let c = Config { name: String::from("app") };
    println!("配置:{}", c.name);
}

为什么需要重导出 ​

内部模块结构往往比较复杂,但使用者不需要知道这些细节。pub use 让你可以把深层嵌套的项"提升"到顶层,提供一个简洁的公开 API。

rust
// 内部结构比较深
mod database {
    pub mod connection {
        pub struct Pool {
            pub size: u32,
        }

        impl Pool {
            pub fn new(size: u32) -> Self {
                Pool { size }
            }
        }
    }

    pub mod query {
        pub fn execute(sql: &str) -> String {
            format!("执行: {}", sql)
        }
    }
}

// 不用 pub use:使用者需要写很长的路径
// database::connection::Pool::new(10)
// database::query::execute("SELECT ...")

// 用 pub use:把常用的项提升到顶层
pub use database::connection::Pool;
pub use database::query::execute;

fn main() {
    // 使用者可以直接用短路径
    let pool = Pool::new(10);
    println!("连接池大小: {}", pool.size);

    let result = execute("SELECT * FROM users");
    println!("{}", result);
}

重导出整个模块 ​

rust
mod services {
    pub mod auth {
        pub fn login(user: &str) -> bool {
            println!("{} 登录成功", user);
            true
        }

        pub fn logout(user: &str) {
            println!("{} 已登出", user);
        }
    }

    pub mod cache {
        pub fn get(key: &str) -> Option<String> {
            println!("缓存查询: {}", key);
            Some(format!("value_of_{}", key))
        }

        pub fn set(key: &str, value: &str) {
            println!("缓存设置: {} = {}", key, value);
        }
    }
}

// 重导出整个子模块
pub use services::auth;
pub use services::cache;

fn main() {
    // 通过重导出的模块名访问
    auth::login("张三");
    cache::set("token", "abc123");

    if let Some(val) = cache::get("token") {
        println!("获取到: {}", val);
    }

    auth::logout("张三");
}

pub use 与 as 组合 ​

重导出的同时可以重命名。

rust
mod implementation {
    pub struct InternalDatabaseConnectionManager {
        pub host: String,
        pub port: u16,
    }

    impl InternalDatabaseConnectionManager {
        pub fn new(host: &str, port: u16) -> Self {
            InternalDatabaseConnectionManager {
                host: host.to_string(),
                port,
            }
        }

        pub fn connect(&self) -> String {
            format!("连接到 {}:{}", self.host, self.port)
        }
    }

    pub fn internal_format_connection_string(host: &str, port: u16) -> String {
        format!("{}:{}", host, port)
    }
}

// 重导出并重命名为更简洁的名字
pub use implementation::InternalDatabaseConnectionManager as DbManager;
pub use implementation::internal_format_connection_string as format_conn;

fn main() {
    let manager = DbManager::new("localhost", 5432);
    println!("{}", manager.connect());
    println!("连接字符串: {}", format_conn("127.0.0.1", 3306));
}

prelude 模式 ​

很多 Rust 库会创建一个 prelude 模块,用 pub use 把最常用的类型集中在一起,使用者只需要 use library::prelude::* 就能导入所有常用项。

rust
mod models {
    pub struct User {
        pub name: String,
    }

    pub struct Product {
        pub title: String,
        pub price: f64,
    }

    pub struct Order {
        pub id: u64,
        pub items: Vec<String>,
    }
}

mod traits {
    pub trait Displayable {
        fn display_info(&self) -> String;
    }

    pub trait Searchable {
        fn matches(&self, query: &str) -> bool;
    }
}

mod utils {
    pub fn format_price(price: f64) -> String {
        format!("¥{:.2}", price)
    }
}

// prelude 模块:集中重导出常用项
pub mod prelude {
    pub use super::models::{User, Product, Order};
    pub use super::traits::{Displayable, Searchable};
    pub use super::utils::format_price;
}

// 使用者只需要一行导入
use prelude::*;

impl Displayable for User {
    fn display_info(&self) -> String {
        format!("用户: {}", self.name)
    }
}

impl Displayable for Product {
    fn display_info(&self) -> String {
        format!("{} ({})", self.title, format_price(self.price))
    }
}

impl Searchable for Product {
    fn matches(&self, query: &str) -> bool {
        self.title.contains(query)
    }
}

fn main() {
    let user = User { name: String::from("张三") };
    let product = Product { title: String::from("Rust 教程"), price: 99.9 };

    println!("{}", user.display_info());
    println!("{}", product.display_info());
    println!("搜索 'Rust': {}", product.matches("Rust"));
}

基本示例 ​

用 pub use 设计一个库的公开 API:

rust
// 内部实现模块(使用者不需要知道这些结构)
mod engine {
    pub mod parser {
        pub fn parse(input: &str) -> Vec<String> {
            input.split_whitespace()
                .map(|s| s.to_string())
                .collect()
        }
    }

    pub mod processor {
        pub fn process(tokens: &[String]) -> String {
            tokens.iter()
                .map(|t| t.to_uppercase())
                .collect::<Vec<_>>()
                .join(" ")
        }
    }

    pub mod formatter {
        pub fn format_output(result: &str) -> String {
            format!(">>> {} <<<", result)
        }
    }
}

// 公开 API:只暴露使用者需要的函数
pub use engine::parser::parse;
pub use engine::processor::process;
pub use engine::formatter::format_output;

// 提供一个便捷的组合函数
pub fn transform(input: &str) -> String {
    let tokens = parse(input);
    let processed = process(&tokens);
    format_output(&processed)
}

fn main() {
    // 使用者可以用顶层的简洁 API
    println!("{}", transform("hello rust world"));

    // 也可以分步调用
    let tokens = parse("step by step");
    let result = process(&tokens);
    let output = format_output(&result);
    println!("{}", output);
}

常见问题 ​

问题一:pub use 和 pub mod 有什么区别?

写法作用外部访问方式
pub mod child公开子模块parent::child::item
pub use child::item重导出子模块的项parent::item

pub mod 公开模块本身,使用者需要知道模块结构。pub use 重导出项,使用者不需要知道内部结构。

问题二:pub use 会影响原始路径吗?

不会。原始路径仍然可用。pub use 只是增加了一条新的访问路径,不会删除或改变原有的路径。

问题三:pub use 导出的项在文档中会怎样显示?

cargo doc 会把 pub use 的项显示在当前模块的文档中,就像它们是在当前模块定义的一样。这正是 pub use 对库设计的价值——让文档结构更清晰。

问题四:什么时候不应该用 pub use?

如果内部结构本身就很清晰且层次不深,没有必要重导出。过度使用 pub use 会让项的真实位置变得模糊,增加维护难度。

适用场景 ​

  • 简化 API:把深层嵌套的项提升到顶层模块
  • prelude 模式:集中导出最常用的类型和 trait
  • 隐藏内部结构:让使用者不需要了解库的内部模块组织
  • 库版本兼容:内部重构后用 pub use 保持原有的公开路径不变
  • 重命名导出:用 pub use ... as ... 提供更好的名字

注意事项 ​

  • pub use 同时导入和公开——外部代码可以通过当前模块访问
  • 原始路径不受影响,pub use 只是增加了一条新路径
  • pub use 的项会出现在 cargo doc 的文档中
  • 可以和 as 组合使用来重命名导出
  • 不要过度重导出,保持 API 的清晰和可预测性
  • prelude 模块是 pub use 最经典的应用模式

总结 ​

pub use 把其他模块的项导入并公开到当前模块,让外部代码可以通过当前模块的路径来访问。它的核心价值是解耦内部实现结构和公开 API——内部可以自由组织和重构模块,通过 pub use 保持对外接口不变。最经典的应用是 prelude 模式:把库中最常用的类型和 trait 集中重导出到一个 prelude 模块中,使用者只需要 use lib::prelude::* 就能获得所有常用项。pub use 还可以配合 as 重命名,为导出的项提供更合适的名字。