Search code examples
rustrust-cargo

Can not add dependency on lib.rs if main.rs is in the same crate in workspace if the package name equals the bin name


I got this cargo toml file:

[package]
edition.workspace = true
name = "batch_jobs"
version.workspace = true

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

[lib]
name = "batch_jobs_lib"
path = "src/lib.rs"

In another crate I want to add a dependency on batch_jobs_lib. I am unable to do so. Cargo complains it can not find the crate. When I change the naming of the [[bin]] section, I get it working but I am just wondering what is wrong with this code.

In another crate in the same workspace I tried declaring the dependency like this:

batch_jobs_lib = { path = "../batch_jobs" }

I get this error: error: no matching package named batch_jobs_lib found

When using this code, I am unable to access the lib's code:

batch_jobs = { path = "../batch_jobs" }

Even worse, Rust can not even find any package but is happy to add the dependency.

Am I missing something or did I misconfigure my toml file and this is not allowed/possible?


Solution

  • The keys in the toml table [dependencies] refer to the package names, not the crates, in the source it's the other way around. Naming the library crate differently from the package is very unorthodox, but still possible, it'll mean you have to refer to the library differently in the source than in the Cargo.toml though:

    [dependencies]
    batch_jobs = { path = "../batch_jobs" }
    

    and in the source code of the crate depending on batch_jobs

    use batch_jobs_lib::*;
    

    It'd be much better to just rely on the defaults and omit the [lib] section off your batch_jobs/Cargo.toml