为什么不能从同一目录中的其他文件导入模块? [英] Why can't I import module from different file in same directory?
问题描述
我的目录结构:
src
main.rs
image.rs
decoders.rs
当我尝试将我的解码器模块导入image.rs时,我得到了:
When I try to import my decoders module in image.rs I get this:
error[E0583]: File not found for module `decoders`
decoders.rs:
decoders.rs:
pub mod Decoders {}
image.rs:
mod decoders
use decoders::Decoders
pub mod Image {}
注意:我使用的模块是有意包装整个文件的模块,因此我可以将属性放在整个文件上.这就是为什么它不是>如何重复的原因包含来自同一项目的另一个文件中的模块?
Note: I am using a module that wraps the entire file on purpose that's I can put attributes on entire files. This is why it's not a duplicate of How to include module from another file from the same project?
奇怪的是,当我尝试在main.rs中导入Image时,此语法工作得很好:
The weird thing is, is that this syntax works perfectly fine when I try to import Image in main.rs:
mod image;
use image::Image;
推荐答案
正在发生的事情是,当您尝试在image.rs
中导入decoders::Decoders
时,您需要进行下一个升级,因为使用了以下方法:>
What's happening is that when you try to import decoders::Decoders
in image.rs
, you need to go through the next level up, because using this:
mod decoders
use decoders::Decoders
表示decoders
现在将是所有者"或在image
下,这是不可能的,因为仅 lib.rs
,mod.rs
或main.rs
文件可以在其他文件中具有模块.因此,要解决此问题,您可以将文件结构更改为此:
Means that decoders
will now be "owned" or under image
, which is impossible since only lib.rs
, mod.rs
or main.rs
files can have modules in other files. So, to fix this, you can either change your file structure to this:
src
main.rs
image
mod.rs
decoder.rs
或者,在main.rs
中使用它:
mod decoders;
mod image;
,并且在image.rs
中是这样的:
use super::decoders::Decoders;
//Or alternatively
use crate::decoders::Decoders;
此外,要解决嵌套mod问题,请在decoders.rs
中执行以下操作:
Also, to fix your nested-mod problem, do the following in decoders.rs
:
//Your code, no `mod Decoders`
以及以下具有mod decoders
语句的位置:
and the following where you have your mod decoders
statement:
#[your_attribs]
mod decoders;
这篇关于为什么不能从同一目录中的其他文件导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!