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

1

10

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.

Nestling answered 23/10, 2019 at 12:59 Comment(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 ?Pilfer
It's hard to answer your question because it doesn't include a minimal reproducible example. 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 you can use to reduce your original code for posting here. Thanks!Skaw
Following edit: A lib usually has a lib.rs file, not a main.rs one. That's probably your first problem.Pilfer
S
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:

Skaw answered 23/10, 2019 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.