rust - 我可以使用单个 Cargo.toml 指定存储库结构,但可以使用多个版本的代码,每个版本都有单独的 main.rs 文件吗?

标签 rust rust-cargo

我正在写一本关于嵌入式 Rust 的书,使用 mdbook 作为一个 git 存储库,然后我有另一个由 cargo 创建的存储库,我在其中放置代码。

我想构建代码,使其与书中的章节相对应,因此位于单独的目录中。

本书的结构:

├── book
├── book.toml
└── src
    ├── chapter_1.md
    ├── chapter_2.md
    ├── chapter_3.md
    ├── chapter_4.md
    ├── chapter_5.md
    ├── chapter_6.md
    └── SUMMARY.md

以及代码的结构:

├── aarch64-unknown-none.json
├── Cargo.lock
├── Cargo.toml
├── layout.ld
├── Readme.md
├── chapter1
│   └── main.rs
├── chapter2
│   ├── boot.rs
│   └── main.rs
└── chapter3
    ├── boot.rs
    ├── console.rs
    └── main.rs

我更喜欢这种结构,因为读者可以直接查看本章的代码,而不是搜索 git 提交。有时我还需要稍后修改一些东西,因此 git 提交不是解决方案。

有没有办法在 Cargo.toml 中指定这种格式?构建所有目录或在命令行中指定哪个目录。

最佳答案

可以在 second edition of the Rust book 中找到确切的解决方案举个例子。

我像这样重构了存储库:

├── aarch64-unknown-none.json
├── Cargo.lock
├── Cargo.toml
├── layout.ld
├── Readme.md
├── chapter1
│   ├── Cargo.toml
│   └── main.rs
├── chapter2
│   ├── boot.rs
│   ├── Cargo.toml
│   └── main.rs
└── chapter3
    ├── boot.rs
    ├── Cargo.toml
    ├── console.rs
    └── main.rs
chapter 目录中的

Cargo.toml 文件没有任何修改。只有根目录中的 Cargo.toml 被修改为包含以下内容:

[workspace]
members = ["chapter1", "chapter2", "chapter3"]

这个解决方案的一个小缺点是成员必须在他们的 Cargo.toml 中有不同的 crate 名称,因为所有成员的输出都存储在 target 目录中工作区的根。这只是一个小问题,我很欣赏 Cargo 提供的灵 active 。

关于rust - 我可以使用单个 Cargo.toml 指定存储库结构,但可以使用多个版本的代码,每个版本都有单独的 main.rs 文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301531/

相关文章:

rust - 返回对链表元素的引用

rust - 找不到tokio::main宏?

build - 使用 Rust Cargo 进行构建的不同目标名称

rust - 如果 "cargo build"比直接运行 rustc 慢,我为什么要使用 Cargo?

rust - 创建向上或向下步进的迭代器

tree - 有没有一种方法可以在没有运行时开销的情况下构建具有循环链接的结构?

operator-overloading - 参数化结构的运算符依赖于另一个运算符

rust - 为什么将 mut 添加到传递的 Iterator 引用可以解决这个问题?

rust - 这是什么意思? "This is precisely because a library should not be deterministically recompiled for all users of the library."

testing - 通过使用 "cargo test"的功能标志运行其他测试