Search code examples
rustrust-cargorust-crates

Unresolved import when importing from a local crate with a main.rs file


I have included a library as a submodule in my program. The structure looks like this:

.
├── my_lib/
│    ├── Cargo.toml
│    └── src/
│         ├── lib/
│         │    ├── mod.rs
│         │    └── foo.rs
│         └── main.rs
├── src/
│    └── main.rs
└── Cargo.toml

In my program's Cargo.toml file I have added the dependency following this answer:

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

However I'm not able to use this library inside my program, I'm a bit new to Rust and this import system is very confusing to me. I've tried this in main.rs:

use my_lib::foo;

But I get an unresolved import 'my_lib' error.


Solution

  • A crate can be either a library or an executable, not both. Your my_lib contains a main.rs file, which means Cargo will treat it as an executable file. You cannot import from an executable.

    You will need to restructure your code. Perhaps you actually meant for my_lib to be a library, in which case it should have a top-level lib.rs. You probably want to:

    • delete my_lib/src/main.rs
    • move my_lib/src/lib/mod.rs to my_lib/src/lib.rs
    • move my_lib/src/lib/foo.rs to my_lib/src/foo.rs

    See also: