当我用 rustc 编译时,为什么我得到 "can't find crate" 被列为 Cargo.toml 中的依赖项?

Why do I get "can't find crate" that is listed as a dependency in Cargo.toml when I compile with rustc?

我的Cargo.toml包括这个:

[dependencies]
chrono = "0.4"

我的代码包括:

extern crate chrono;
use chrono::{Duration, DateTime, Utc};

然而当我 运行 我的代码时,我得到这个错误:

error[E0463]: can't find crate for `chrono`
 --> src/lib.rs:1:1
  |
1 | extern crate chrono;
  | ^^^^^^^^^^^^^^^^^^^^ can't find crate

我正在做一项运动练习,所以我 building/running 程序的方式是 rustc src/lib.rs 来测试我的解决方案。是因为我不是运行宁rustc src/main.rs吗?

当您直接 运行 rustc 时,编译器只知道命令行参数。它对 Cargo.toml 一无所知,尤其是,因此它不知道到哪里寻找 chrono 库。

要使用依赖管理,你必须用 Cargo 编译你的项目 - 只需使用 cargo build/cargo run/cargo test,一切都应该没问题。有关详细信息,请参阅 the Book

但是,如果您想(出于某种原因)直接使用 rustc,我建议无论如何先检查 cargo,使用 cargo build --verbose。它将显示所有调用的命令,允许您检查可能手动定义的参数。