无法从另一个板条箱导入模块 - 未解析的导入 [英] Can't import a module from another crate - unresolved import
问题描述
我正在尝试编写一个名为 bar
的 crate,结构如下
I am trying to write a crate called bar
, the structure looks like this
src/
├── bar.rs
└── lib.rs
我的 src/lib.rs
看起来像这样
#![crate_type = "lib"]
#![crate_name = "bar"]
#![feature(ip_addr)]
#[allow(dead_code)]
pub mod bar;
我的 bar.rs
有
pub struct baz {
// stuff
}
impl baz {
// stuff
}
现在当我尝试在另一个板条箱中使用这个板条箱时:
Now when I try to use this crate in another crate like:
extern crate bar;
use bar::baz;
fn main() {
let cidr = baz::new("Hi");
println!("{}", cidr.say());
}
这失败了
error: unresolved import `bar::baz`. There is no `baz` in `bar`
我需要在其他地方声明模块吗?
Do I need to declare the module somewhere else?
推荐答案
你缺少的重要部分是 crate 定义了它们自己的模块.也就是说,您的 crate bar
隐式定义了一个名为 bar
的模块,但您还创建了一个名为 bar
在里面.您的结构驻留在此嵌套模块中.
The important part you are missing is that crates define their own module. That is, your crate bar
implicitly defines a module called bar
, but you also have created a module called bar
inside that. Your struct resides within this nested module.
如果您将 main 更改为 use bar::bar::baz;
,您可以继续前进.您必须决定这是否是您想要的结构.大多数惯用的 Rust 项目不会有额外的 mod
并将其扁平化:
If you change your main to use bar::bar::baz;
you can progress past this. You will have to decide if that's the structure you want though. Most idiomatic Rust projects would not have the extra mod
and would flatten it out:
src/lib.rs
pub struct Baz {
// stuff
}
impl Baz {
// stuff
}
不幸的是,您的示例代码无法编译,因为您具有无效的结构定义,并且您调用了不存在的方法 (new
),因此我无法告诉您还需要什么编译.
Unfortunately, your example code cannot compile, as you have invalid struct definitions, and you call methods that don't exist (new
), so I can't tell you what else it will take to compile.
此外,结构体应该是 PascalCase
.
Also, structs should be PascalCase
.
这篇关于无法从另一个板条箱导入模块 - 未解析的导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!