RUST:有没有更优雅的方式来导入 mod?
这是我的项目结构:
.
└── src
├── main.rs
├── sub_folder
│ └── mod.rs
└── sub_mod.rs
在 sub_mod.rs
中,如果我像这样导入 sub_folder/
,货物不会警告我:
#[path = "./sub_folder/mod.rs"]
mod sub_folder;
但我不能这样做
mod sub_folder
,但在 main.rs 中它有效!
sub_mod.rs
中是否有更温和的方法来导入 sub_folder/
?
Here is my project structure:
.
└── src
├── main.rs
├── sub_folder
│ └── mod.rs
└── sub_mod.rs
in sub_mod.rs
, cargo won't warn me if I import sub_folder/
like:
#[path = "./sub_folder/mod.rs"]
mod sub_folder;
but I cannot do
mod sub_folder
but in main.rs
it works!!
Is there a gentler way in sub_mod.rs
to import sub_folder/
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你几乎不应该使用
#[path]
属性。它用于将源代码放在非标准位置,并且很容易制作使用它的错误。相反,请确保您的mod
声明和文件位置相互匹配。因此,如果路径是
src/sub_folder/mod.rs
(或src/sub_folder.rs
),那么您应该在main.rs< 中声明该模块/code> 因为
main.rs
(或者lib.rs
如果您这样做)是 crate 根,即声明所有顶级模块的地方。也就是说,main.rs
包含这两个模块是板条箱内的兄弟。然后,为了让
sub_mod
导入(不是定义)sub_folder
,它应该包含:或者,等效地(绝对路径而不是相对路径),
A提示:如果您使用与 rust-analyzer 兼容的编辑器,您可以让它帮助您正确创建模块。不要创建文件;相反,在现有源代码中的某处写入
mod my_module;
,等待出现“丢失文件”错误,然后运行提供的修复“创建模块”。 rust-analyzer 会在正确的位置为您创建该文件。You should almost never use the
#[path]
attribute. It is for putting source code in nonstandard locations, and it is very easy to make a mistake using it. Instead, make sure yourmod
declarations and your file locations match up to each other.So, if the path is
src/sub_folder/mod.rs
(orsrc/sub_folder.rs
), then you should declare the module inmain.rs
becausemain.rs
(orlib.rs
if you are doing that instead) is the crate root, the place where all top-level modules are declared. That is,main.rs
containsThese two modules are siblings within the crate. Then in order for
sub_mod
to import (not define)sub_folder
, it should contain:or, equivalently (absolute rather than relative path),
A tip: If you are using an editor compatible with
rust-analyzer
, you can have it help you with creating modules properly. Don't create a file; instead, writemod my_module;
somewhere in your existing sources, wait for the "missing file" error to appear, then run the offered fix “Create module”. rust-analyzer will create the file in the correct location for you.