对 Rust 模块感到困惑 [英] Confused about rust modules

查看:83
本文介绍了对 Rust 模块感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 src/ 中有三个文件,如下所示:

I have three files in src/, like so:

lib.rs

pub mod first

first.rs

fn hello() {}

main.rs

pub mod lib

这给了我一个错误说:

error[E0583]: file not found for module `first`
 --> src/lib.rs:1:9
  |
1 | pub mod first;
  |         ^^^^^
  |
  = help: name the file either lib/first.rs or lib/first/mod.rs inside the directory "src"

现在,如果我从 main.rs 中删除 pub mod lib,一切都可以正常编译.

Now, if I remove pub mod lib from main.rs, everything compiles fine.

我不明白为什么会这样.

I don't understand why this is happening.

推荐答案

编译器说的帮助很有意义.当您在 lib.rs 内编写 pub mod first; 时,它会检查 first.rs 文件或 first> lib 文件夹和 mod.rs 文件中的文件夹.

The help that compiler says is very meaningful. When you write pub mod first; inside of a lib.rs it checks for the first.rs file or first folder inside a lib folder and a mod.rs file.

请注意,mod.rs 的用法在 Rust 2018 中发生了变化.参考

Please note that mod.rs usages are changed with Rust 2018. Reference

现在,如果我从 main.rs 中删除 pub mod lib,一切都可以正常编译.

Now, if I remove pub mod lib from main.rs, everything compiles fine.

当您从主文件中删除 pub mod lib; 时,

When you remove pub mod lib; from your main,

您基本上是说此代码不会用于生产,因此甚至不需要编译.所以基本上不会包含代码来编译.

You basically say that this code will not be used in production therefore it is not needed to compile even. So basically the code will not included to compile.

这就是为什么当您删除 pub mod lib;

This is why it works when you remove the pub mod lib;

这篇关于对 Rust 模块感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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