简体   繁体   English

从带有 main.rs 文件的本地 crate 导入时未解决的导入

[英]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 :在我的程序的Cargo.toml文件中,我在这个答案之后添加了依赖项:

[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.但是我不能在我的程序中使用这个库,我对 Rust 有点陌生,这个导入系统让我很困惑。 I've tried this in main.rs :我在main.rs试过这个:

use my_lib::foo;

But I get an unresolved import 'my_lib' error.但我得到一个unresolved import 'my_lib'错误。

A crate can be either a library or an executable, not both. crate 可以库或可执行文件,不能同时是两者。 Your my_lib contains a main.rs file, which means Cargo will treat it as an executable file.您的my_lib包含一个main.rs文件,这意味着 Cargo 会将其视为可执行文件。 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 .也许您实际上是想让my_lib成为一个库,在这种情况下,它应该有一个顶级lib.rs You probably want to:您可能想要:

  • delete my_lib/src/main.rs删除my_lib/src/main.rs
  • move my_lib/src/lib/mod.rs to my_lib/src/lib.rsmy_lib/src/lib/mod.rs 移动my_lib/src/lib.rs
  • move my_lib/src/lib/foo.rs to my_lib/src/foo.rsmy_lib/src/lib/foo.rs 移动my_lib/src/foo.rs

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM