首页 > 解决方案 > 我可以使用单个 Cargo.toml 但多个版本的代码指定存储库结构,每个版本都有单独的 main.rs 文件吗?

问题描述

我正在写一本关于嵌入式 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 中指定这种格式?要么构建所有目录,要么在命令行上指定哪个目录。

标签: rustrust-cargo

解决方案


确切的解决方案可以在第二版的 Rust 书中找到一个示例。

我像这样重组了存储库:

├── 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

Cargo.toml章节目录中的文件保持不变。仅Cargo.toml根中的 被修改为包含以下内容:

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

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


推荐阅读