为什么我不能从同一目录中的不同文件导入模块? [英] Why can't I import module from different file in same directory?

查看:25
本文介绍了为什么我不能从同一目录中的不同文件导入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目录结构:

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 {}

注意:我正在使用一个模块来包装整个文件,我可以将属性放在整个文件上.这就是为什么它不是 How to包含来自同一项目的另一个文件的模块?

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 下,这意味着编译器将在 image 子目录中搜索 decoders.rs.因此,要解决此问题,您可以将文件结构更改为:

Means that decoders will now be "owned" or under image, which means that the compiler will search in the image subdirectory for decoders.rs. So, to fix this, you can either change your file structure to this:

src/
    main.rs
    image.rs        ** or image/mod.rs
    image/
        decoder.rs

或者,在 main.rs 中使用它:

Or, use this in main.rs:

mod decoders;
mod image;

image.rs 中:

use super::decoders::Decoders;
//Or alternatively
use crate::decoders::Decoders;

此外,要解决嵌套模式问题,请在 decoders.rs 中执行以下操作:

Also, to fix your nested-mod problem, do the following in decoders.rs:

//Your code, no `mod Decoders`

以及以下您的 mod 解码器 语句:

and the following where you have your mod decoders statement:

#[your_attribs]
mod decoders;

这篇关于为什么我不能从同一目录中的不同文件导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆