Doubts about bin section in rust workspace

I encountered a compilation problem, can not understand, hope to get help!
the error message is as follows:

error[E0432]: unresolved import `chrono`
 --> refer/src/main.rs:1:5
  |
1 | use chrono::Utc;
  |     ^^^^^^ use of undeclared crate or module `chrono`

What is the cause of the error and how to solve the compilation problem?
Any suggestion is appreciated.

The test code directory structure is as follows:

.
├── Cargo.lock
├── Cargo.toml
└── refer
    ├── Cargo.toml
    └── src
        └── main.rs

3 directories, 4 files

this workspace just include a binary package(refer),workspace Cargo.toml:

[package]
name = "workspace_db"
version.workspace = true
edition.workspace = true
authors.workspace = true

[[bin]]
name = "refer"
path = "refer/src/main.rs"

[workspace]
members = ["refer"]

[workspace.dependencies]
chrono = "0.4.38"

[workspace.package]
version = "0.1.0"
edition = "2021"
authors = ["workspace_db@gmail.com"]
license = "GPL"

binary package Cargo.toml:

[package]
name = "refer"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true

[dependencies]
chrono.workspace = true

refer/src/main.rs:

use chrono::Utc;

fn main() {
    println!("Hello, world! Now time {}", Utc::now());
}

This looks odd to me. Try removing this section from your workspace manifest and try again, please. The [package] section also looks out of place. I think what you want is a virtual workspace.

I believe thanks to the [[bin]] section in your root package, Cargo treats the refer binary as part of said root package for whatever Cargo command you ran, not as part of the refer workspace member. Your root package does not declare chrono as a dependency, hence the error message.

2 Likes

You`r right. I try these two solutions: 1. remove the bin section; 2.add dependencies section in root package Cargo.toml, both solutions work. Thanks very much.

I assume you added the [[bin]] to your workspace because you had troubles with the discovery of your binary? If you don't want your workspace to be virtual but still want to be able to run cargo run --bin refer without the need of specifiying which package refer comes from (which you'd do by adding -p refer as a CLI argument), you can add refer to the default-members of your workspace.

Please go ahead and mark the post from @jofas that solved your problem as the solution by checking the box at the bottom of that post. This marks the solution as solved, so others know it is resolved and they can quickly find the solution if they have a similar problem.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.