rust - 如何将库中的源文件导入 build.rs?
问题描述
我有以下文件结构:
src/
lib.rs
foo.rs
build.rs
我想从foo.rs
(lib.rs
已经pub mod foo
在里面)导入一些东西到build.rs
. (我正在尝试导入一个类型以便在构建时生成一些 JSON 模式)
这可能吗?
解决方案
你不能干净地 - 构建脚本用于构建库,因此根据定义必须在构建库之前运行。
清洁溶液
将类型放入另一个库并将新库导入构建脚本和原始库
.
├── the_library
│ ├── Cargo.toml
│ ├── build.rs
│ └── src
│ └── lib.rs
└── the_type
├── Cargo.toml
└── src
└── lib.rs
the_type/src/lib.rs
pub struct TheCoolType;
the_library/Cargo.toml
# ...
[dependencies]
the_type = { path = "../the_type" }
[build-dependencies]
the_type = { path = "../the_type" }
the_library/build.rs
fn main() {
the_type::TheCoolType;
}
the_library/src/lib.rs
pub fn thing() {
the_type::TheCoolType;
}
哈克解决方案
使用类似#[path] mod ...
或include!
包含代码两次。这基本上是纯文本替换,因此非常脆弱。
.
├── Cargo.toml
├── build.rs
└── src
├── foo.rs
└── lib.rs
构建.rs
// One **exactly one** of this...
#[path = "src/foo.rs"]
mod foo;
// ... or this
// mod foo {
// include!("src/foo.rs");
// }
fn main() {
foo::TheCoolType;
}
src/lib.rs
mod foo;
pub fn thing() {
foo::TheCoolType;
}
src/foo.rs
pub struct TheCoolType;
推荐阅读
- excel - 搜索工作表中的值
- javascript - 具有完整链接平滑滚动的锚点
- azure - 在 Azure AD 的 MultiTenant 应用程序中允许或限制特定 Tetant 的用户
- python - TypeError: 'pygame.Surface' 对象不可调用(数组有问题,在 Pygame 中)
- cmake - 没有找到所需的“libconfig++”
- rust - 函数中泛型类型的访问字段
- mysql - SUM 和 COUNT 在复杂的 SQL QUERY 中不起作用
- reactjs - 当“jsx”为“react-jsx”时,除非提供“--jsx”标志,否则无法使用 JSX
- python - 部署不和谐机器人时丢失 csv 数据 - python
- swift - 禁用 Crashlytics 调试日志记录