【问题标题】:Rust: no `module` in the rootRust:根目录中没有“模块”
【发布时间】:2021-06-29 04:22:42
【问题描述】:

当我在src/cmdline.rs 中运行use crate::feed; 时,我希望它会导入src/feed.rs,但事实并非如此。相反,我得到了,

error[E0432]: unresolved import `crate::feed`
 --> src/cmdline.rs:2:5
  |
2 | use crate::feed;
  |     ^^^^^^^^^^^ no `feed` in the root

尽管src/feed.rs 存在。但是,如果我恐慌并将其更改为mod feed;,那么我会得到

error[E0583]: file not found for module `feed`
 --> src/cmdline.rs:2:1
  |
2 | mod feed;
  | ^^^^^^^^^
  |
  = help: to create the module `feed`, create file "src/cmdline/feed.rs"

使用mod super::

error: expected identifier, found keyword `super`
 --> src/cmdline.rs:2:5
  |
2 | mod super::feed;
  |     ^^^^^ expected identifier, found keyword

或者use super::

error[E0432]: unresolved import `super::feed`
 --> src/cmdline.rs:2:5
  |
2 | use super::feed;
  |     ^^^^^^^^^^^ no `feed` in the root

相关文件的文件结构如下所示,

src/feed.rs
src/cmdline.rs
src/main.rs

【问题讨论】:

  • src/feed.rs 存在吗?在src/lib.rs(或main.rs)你有mod feed;
  • @prog-fh 已更新。

标签: import rust


【解决方案1】:

因此,我能够按照您描述的方式使我的导入工作的一种方法是执行以下操作。

首先在main.rs 中导入模块cmdline 以及我希望能够通过crate:: 使用的每个模块。

// file src/main.rs
mod cmdline;
mod feed; // <== import module to be able to use via `crate::feed`

fn main() {
  cmdline::do_something();
}

然后在cmdline.rs 我使用create::feed。

// file src/cmdline.rs

use crate::feed; // <== import sibling module

pub fn do_something() {
  feed::do_something_else();
}

我的feed.rs 看起来像这样。

// file src/feed.rs
pub fn d_something_else() {
  // ...
}

根据我从实验中了解到的情况,您需要首先在 main.rs 中使用 mod 来定义您的 crate 中包含哪些模块。

【讨论】:

    【解决方案2】:

    我想通了。 rust 模块系统不允许导入同级文件,

    • src/a.rs
    • src/b.rs

    句号:a.rs 无法导入 b.rs。它会做的是尝试从

    • src/a/b.rs

    如果你在这个答案上,这对你来说可能没有任何意义,而且你已经浪费了几个小时。这是我困惑的根源:

    • src/main.rs

    其实很特别。在src/main.rs 内部,mod 将导入同级文件(以及现在已弃用的mod.rs;或lib.rs)。但关键是你自己的 rust 文件不能使用兄弟文件中的 rust 代码。

    【讨论】:

    • main.rs 在这个意义上并不特殊。 Rust 使用提供的 mod _; 用法构建模块层次结构。当您尝试 use crate::feed 时,它会查看 main 模块(因为它是 crate 根),并检查名为 feed 的模块是否连接到它。由于不是(因为您没有在 main.rs 中包含 mod feed;),因此编译器会出错。我要说的是,虽然模块系统非常清晰并且不那么难(仅在最初)理解,但迄今为止,模块层次结构的显式创建对我没有用处,因为我只是模仿实际的文件层次结构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多