未能解析清单 - 未指定目标

failed to parse manifest - no targets specified

我是 Rust 的新手,正在尝试使用 Cargo 构建一个测试项目。我的 Cargo.toml 看起来像:

[package]
name = "rust-play"
version = "0.0.1"
authors = [ "Bradley Wogsland <omitted>" ]

(但实际的 TOML 文件并没有省略我的电子邮件)。当我 cargo build 时出现以下错误:

error: failed to parse manifest at /Users/wogsland/Projects/rust-play/Cargo.toml

Caused by: no targets specified in the manifest either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] section must be present

我的 main 函数在 src/test.rs 文件中。我需要在 TOML 文件中指定吗?如果是这样,如何?我尝试添加

target = "src/test.rs"

无果。

如错误所述:

either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] section must be present

所以直接的答案是 add a [[bin]] section:

[[bin]]
name = "test"
path = "src/test.rs"

但是,将文件放在预期位置更为常见:src/main.rs。如果您计划拥有多个二进制文件,也可以将其放在 src/bin/test.rs 中。

如果它实际上是为了测试您的代码,那么单元测试将与它们正在测试的代码放在同一个文件中,而集成测试将放在 tests/foo.rs.

在我的情况下,也可能在您的情况下,rs 文件未命名为 main.rs,而 Cargo 假定 src/main.rs 是二进制包的包根。因此,规则是如果项目是可执行文件,则将主源文件命名为 src/main.rs。如果是库,将主源文件命名为src/lib.rs.

此外,Cargo 还将把位于 src/bin/*.rs 中的任何文件视为可执行文件,如上一个答案中所述。

总结:

如果您使用cargo new xxx --bin,您会发现src 目录中的文件名为main.rs。当您检查文件时 Cargo.toml。跟你写的一样。所以第一种方式就是将src中的文件改成main.rs

作为货物报告,我们可以使用[[bin]]设置文件。 @Shepmaster 已经解决了

两种方式都可以。

替代问题和解决方案:如果您已将 Cargo.toml 文件复制到 父文件夹[=16],您也可能会遇到此错误=] 的板条箱。

我 运行 在无意中将 Cargo.toml 复制到我的主文件夹后,在 Ubuntu 20.04 遇到了这个问题。尽管我的工作目录有一个正确定义的 Cargo.toml,但 $HOME 中的副本优先并导致构建失败。

我也有这个问题,这是因为父目录也包含一个 Cargo.toml 文件,并且它优先于当前目录中的文件