I am new to Rust and attempting to build a test project with Cargo. My Cargo.toml looks like:

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

(but the actual TOML file doesn't omit my email). When I cargo build I am getting the following error:

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

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

My main function is in a src/test.rs file. Do I need to specify that in the TOML file? If so, how? I tried adding

target = "src/test.rs"

to no avail.

6

Best Answer


As the error says:

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

So the direct answer is to add a [[bin]] section:

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

However, it's far more usual to just place the file in the expected location: src/main.rs. You could also place it in src/bin/test.rs if you plan on having multiple binaries.

If it's actually for testing your code, then unit tests go in the same file as the code they are testing and integration tests go in tests/foo.rs.

Alternative issue and solution: You can also be faced with this error if you have copied Cargo.toml file to a parent folder of the crate.

In my case and probably in your case as well, the rs file was not named main.rs while Cargo assumes that src/main.rs is the crate root of a binary crate. So, the rule is that If project is an executable, name the main source file src/main.rs. If it is a library, name the main source file src/lib.rs.

Additionally, Cargo will also treat any files located in src/bin/*.rs as executables like mentioned in the previous answer.

I ran into this issue on Ubuntu 20.04 after having inadvertently copied Cargo.toml to my home folder. Even though my working directory had a properly defined Cargo.toml, the copy in $HOME was taking precedence and causing builds to fail.

As a summary:

If you use cargo new xxx --bin, you will find the file in the src directory is named main.rs. And when you check the file Cargo.toml. It is the same as you written. So the first way is to change the file in src to main.rs

As the cargo report, we can use the [[bin]] to set the file. @Shepmaster has solved it.

Both two ways can work.

I also had this issue and it was because the parent directory also contained a Cargo.toml file and it was prioritising that over the one in the current directory