9

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Dani M
  • 1,173
  • 1
  • 15
  • 43
  • 3
    why isn't the source of my_lib directly in `my_lib/src` ? I would expect `my_lib/src/lib.rs`. What's that `lib/` directory ? – Denys Séguret Oct 23 '19 at 13:07
  • It's hard to answer your question because it doesn't include a [MRE]. We can't tell what the contents of the `Cargo.toml` files are. You also don't show any Rust files (and their contents) inside of `my_lib`. It would make it easier for us to help you if you try to reproduce your error in a brand new Cargo project, then [edit] your question to include the additional info. There are [Rust-specific MRE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. Thanks! – Shepmaster Oct 23 '19 at 13:15
  • Following edit: A lib usually has a `lib.rs` file, not a `main.rs` one. That's probably your first problem. – Denys Séguret Oct 23 '19 at 13:25

1 Answers1

7

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366