为什么 Rust 需要包和工作区?

问题描述 投票:0回答:2

我对 Rust 模块层次结构中三个上层的存在以及为什么需要它们感到有点困惑。如果我理解正确的话:

  • 板条箱是包含多个模块的简单项目,每个板条箱要么是一个库,要么是一个二进制文件。
  • 软件包包含一个或多个 crate,最多包含一个库。
  • 工作区是一组包。

我理解如果一起开发多个板条箱,则需要将它们放在一起,因此包或工作区对我来说都有意义,但我不明白为什么两者都需要存在以及为什么最多需要 1 个库对包裹的限制。这样做有什么好处?

我读过 Why can a Cargo package only has one library target? 这给出了每个包 1 个库 crate 规则的解释,但这让我更加困惑,因为你仍然可以拥有带有二进制文件甚至“更糟糕”的包没有图书馆。如果包是包管理器 Cargo 的抽象,为什么要允许其中包含二进制文件呢?为什么允许内部没有单个库的包?您可以导入无库包作为依赖项吗?

rust rust-cargo
2个回答
0
投票
Crates:
    They're the unit of compilation in Rust.
    A crate can be a binary (executable) or a library.
    Each crate has its own module hierarchy, and the top-most level is the crate root.

Packages:
    A package contains one or more crates.
    While a package can contain multiple binary crates, it can contain at most one library crate. This is because Cargo, Rust's package manager, uses the package name as the library name when you're importing it as a dependency in another project. Having multiple libraries in a single package would be ambiguous.

Workspaces:
    A workspace allows you to group multiple packages together.
    This is useful when you're working on multiple interdependent packages, and you want them to share the same Cargo.lock file and target directory.

现在,解决您的一些具体问题:

Why there would need to be a maximum of 1 library restriction on packages?

当另一个包依赖于一个包时,它通过名称指定该包。在 Rust 生态系统中,这个名称意味着包中包含的库箱的名称。如果一个包中有多个库,那么引用哪个库就会产生歧义。这是为了确保依赖系统的清晰度和简单性。

If packages are meant to be an abstraction for Cargo, the package manager, why allow binaries in them at all? Why allow packages without a single library inside?

包不仅仅是库的抽象;它们是分发 Rust 代码的抽象。有时,此代码可能是一个实用程序,旨在用作命令行工具而不是库。因此,包可能包含二进制文件但不包含库。相反,包可能包含一个在其他项目中用作依赖项的库。

Can you import a no-library-package as a dependency?

如果包不包含库,则它不能像使用库一样用作依赖项。但您仍然可以将其列为依赖项,以确保它已构建或使用它提供的任何二进制文件。然而,这种情况不太常见。

总而言之,Rust 生态系统中的这些抽象级别允许灵活地组织、分发和构建 Rust 代码,同时保持依赖关系和包管理的清晰度。


-2
投票

我才刚刚开始使用 Rust,但在我看来,带有库和二进制文件的包基本上就是 带有工具(二进制文件)的功能特定库,特定于该库的工具。

示例 - 游戏的 3D 库

图书馆的用户将能够使用这些工具来创建内容,而无需将工具传递给最终用户。

© www.soinside.com 2019 - 2024. All rights reserved.