为什么 cargo 为 rand 包下载 libc?

Why is cargo downloading libc for the rand package?

我正在学习 Rust。作为猜谜游戏的一部分 tutorial, I downloaded the rand crate. I am concerned about dependency confusion,不希望下载任何非绝对必要的软件包。

因此,我将 Cargo.toml 设置为:

[dependencies]
rand = "=0.5.5"

但是,我注意到下载了 3 个不同版本的 rand_core,还有 libc。

    Updating crates.io index
  Downloaded rand_core v0.3.1
  Downloaded rand_core v0.4.2
  Downloaded rand v0.5.5
  Downloaded rand_core v0.2.2
  Downloaded libc v0.2.87
  Downloaded 5 crates (702.2 KB) in 1.17s
   Compiling libc v0.2.87
   Compiling rand_core v0.4.2
   Compiling rand_core v0.3.1
   Compiling rand_core v0.2.2
   Compiling rand v0.5.5
   Compiling guessing_game v0.1.0 (/home/user/projects/learn-rust/guessing_game)
    Finished dev [unoptimized + debuginfo] target(s) in 26.19s
     Running `target/debug/guessing_game`

我在 crates.io 去了 dependencies page for rand 0.5.5,发现:

  1. rand 0.5.5 取决于
  2. rand_core^0.2(我下载的是0.2.2)取决于
  3. rand_core^0.3(我下载的是0.3.1)依赖
  4. rand_core^0.4(我下载的是0.4.2)。

但是,任何地方都不需要依赖 libc。

我为什么要下载 libc?

您可以使用 cargo tree -i <CRATE> 来查看依赖于特定板条箱的内容:

$ cargo tree -i libc
libc v0.2.87
└── rand v0.5.5
    └── guessing_game v0.1.0 (...)

所以randdependencies page for rand 0.5.5 确实说 rand_core 是唯一 必需的 板条箱,但 libc 被列为 可选 .这意味着它由一个功能门控。

您可以查看 cargo tree -i libc -e features 的输出以查看已启用的功能,但它并不十分简单,因为它显示 所有 rand 箱子,而不仅仅是启用 libc.

的箱子

唯一确定的方法是查看 crate's Cargo.toml:

[features]
default = ["std"]
nightly = ["i128_support"]
std = ["rand_core/std", "alloc", "libc", "winapi", "cloudabi", "fuchsia-zircon"]
alloc = ["rand_core/alloc"]
i128_support = []
serde1 = ["serde", "serde_derive", "rand_core/serde1"]

[dependencies]
rand_core = { path = "rand_core", version = "0.2", default-features = false }
log = { version = "0.4", optional = true }
serde = { version = "1", optional = true }
serde_derive = { version = "1", optional = true }

[target.'cfg(unix)'.dependencies]
libc = { version = "0.2", optional = true }

所以 libc 是特征门控和目标门控的。它仅依赖于 unix 平台,并且仅在启用 "std" 功能时使用,由 "default" 启用。您可以指定 default-features = false 选择退出,但请注意,它最终会禁用大部分板条箱。