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

Why should I use Cargo if "cargo build" is slower than running rustc directly?

我创建了一个简单的 hello world 程序:

fn main() {
    println!("Hello, world");
}

使用 rustccargo build 编译代码时,cargo 命令显得较慢。 cargo build 需要 1.6srustc 需要 1s。请参阅屏幕截图右侧的时间戳。

这是为什么?为什么我还要使用 cargo?

作为Pavel Strakhov said

Cargo is not a compiler, it's a package manager. It runs rustc and does some extra work (e.g. resolves dependencies), so it can't be faster than bare rustc.

你可以通过运行 cargo build --verbose自己看看,它输出cargo运行的rustc命令:

$ cargo build --verbose
   Compiling hw v0.1.0 (file:///private/tmp/hw)
     Running `rustc --crate-name hw src/main.rs --crate-type bin --emit=dep-info,link -C debuginfo=2 -C metadata=3c693c67d55ff970 -C extra-filename=-3c693c67d55ff970 --out-dir /private/tmp/hw/target/debug/deps -L dependency=/private/tmp/hw/target/debug/deps`
    Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs

Why should I still use cargo

上面的输出显示了一个原因:查看所有传递给 rustc 的参数。你知道他们每个人的作用吗?你知道吗? Cargo 抽象出一些细节,让您专注于代码。

Cargo 不仅仅是调用编译器。对大多数人最大的好处就是它 manages your dependencies based on versions and allows publishing your own crates as well. It also allows for build scripts which run before your main compilation. It has easy ways of running your tests 和例子。

更有用,Cargo 执行检查以查看是否应该重建

$ time rustc src/main.rs
0:00.21
$ time rustc src/main.rs
0:00.22

$ time cargo build
0:00.41
$ time cargo build
0:00.09                   # Much better!