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

Rust项目结构最佳实践:如何避免common库被二进制外部调用?

Rust项目结构与私有共享代码实现方案

针对你提出的需求——让client和server能复用common库的代码,但外部仅持有client二进制时无法调用common中的方法,有以下几种可行方案:

方案一:工作区+私有路径依赖+编译优化

  1. 保留你设计的工作区结构:
my_awesome_project
├── Cargo.toml(工作区根配置)
├── common(库)
│   └── Cargo.toml
├── client(二进制)
│   └── Cargo.toml
└── server(二进制)
    └── Cargo.toml
  1. 在client和server的Cargo.toml中通过路径依赖引入common,同时在common的Cargo.toml中添加publish = false,避免库被意外发布:
# client/Cargo.toml
[dependencies]
common = { path = "../common" }
  1. 对common中仅内部使用的公开项添加#[doc(hidden)],并在release编译时启用优化:
    在项目根或各二进制的Cargo.toml中配置:
[profile.release]
lto = true
opt-level = 3
strip = "symbols"

编译后的二进制会移除未被client/server实际调用的符号,剩余符号也不会出现在文档中,大幅降低外部逆向调用的可能。

方案二:私有子模块+共享源码引入

如果不想单独维护common库,可将共享代码放在独立目录,通过私有模块引入到client和server中:

my_awesome_project
├── client
│   ├── src
│   │   ├── main.rs
│   │   └── common(私有子模块)
│   │       └── mod.rs
├── server
│   ├── src
│   │   ├── main.rs
│   │   └── common(私有子模块)
│   │       └── mod.rs
└── shared_code(存放共享源码)

在client和server的私有模块中用include!宏引入共享代码:

// client/src/common/mod.rs
include!("../../../shared_code/lib.rs");

这种方式下共享代码会直接编译进二进制,不存在独立的库符号暴露,完全避免外部调用的可能。

方案三:单crate多二进制+pub(crate)可见性限制

调整项目为单crate结构,将common代码放在lib.rs中,用pub(crate)限制可见性:

my_awesome_project
├── Cargo.toml
└── src
    ├── lib.rs(common代码,用pub(crate)暴露)
    ├── bin
    │   ├── client.rs
    │   └── server.rs

pub(crate)标记的项仅在当前crate内部可见,编译后的二进制不会对外暴露这些符号,既能实现代码复用,又保证了私有性。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:55:56