rust - 为什么 Cargo 会下载 rand 包的 libc?

标签 rust rust-cargo

我正在学习 Rust。作为猜谜游戏的一部分tutorial ,我下载了兰特箱。我关心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`

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

  1. 兰特 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> 查看依赖于特定 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 中启用的所有功能 crate ,不仅仅是那些启用 libc 的 crate .

唯一确定的方法是查看 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选择退出它,但请注意,它最终会禁用大部分 crate 。

关于rust - 为什么 Cargo 会下载 rand 包的 libc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66450623/

相关文章:

rust - 按键对 HashMap 数据进行排序

rust - 如何使用 serde 将结构序列化为另一个 Rust 数据结构?

error-handling - 如何捕获 Rust 的 swap_with_slice() vec 方法是否发生错误?

rust - 为什么 cargo build 没有显示具有不兼容依赖项的编译错误?

rust - 使用 C/Fortran 库时 Rust ffi 中 undefined symbol 的问题

rust - 变量值未移动

optimization - Rust 编译器对 `loop` 和 `while true` 做了哪些优化?

rust - Rust 项目中的工作区内依赖关系

rust - Cargo 命令打印目标文件列表?

rust - 在 Rust FFI 中混合静态库和动态库