微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我有以下文件结构:

src/
    lib.rs
    foo.rs
build.rs

我想从 foo.rslib.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;
}

hacky 解决方案

使用 #[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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。