rust - 如何将我的库中的源文件导入 build.rs?

标签 rust rust-cargo build-script

我有以下文件结构:

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
build.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;

关于rust - 如何将我的库中的源文件导入 build.rs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67905320/

相关文章:

iterator - 我该如何编写一个迭代器来返回对自身的引用?

rust - 为什么 Piston text() 需要对字形缓存的可变引用?

sqlite - 如何在 Cargo.toml 中静态链接 sqlite3

reactjs - 添加依赖项会出现错误 : 'react-scripts' is not recognized as an internal or external command, 可运行程序或批处理文件”

rust - 为什么在编译时生成一个包含 ~30K 条目的静态 HashMap 会消耗这么多资源?

rust - "the immutable borrow prevents mutable borrows"当使用 rust-sdl2 抽取事件时

rust - "Unable to update registry: The server name or address could not be resolved"为依赖

rust - 如何在 Rust 循环中返回一个值?

rust - Cargo.toml 可以包含自定义属性吗

java - 如何处理Gradle和多项目配置?