RUST:有没有更优雅的方式来导入 mod?

发布于 2025-01-12 09:48:06 字数 529 浏览 4 评论 0原文

这是我的项目结构:

.
└── 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

謌踐踏愛綪 2025-01-19 09:48:06

你几乎不应该使用#[path]属性。它用于将源代码放在非标准位置,并且很容易制作使用它的错误。相反,请确保您的 mod 声明和文件位置相互匹配。

因此,如果路径是 src/sub_folder/mod.rs (或 src/sub_folder.rs),那么您应该在 main.rs< 中声明该模块/code> 因为 main.rs (或者 lib.rs 如果您这样做)是 crate 根,即声明所有顶级模块的地方。也就是说,main.rs 包含

mod sub_folder;
mod sub_mod;

这两个模块是板条箱内的兄弟。然后,为了让 sub_mod 导入(不是定义)sub_folder,它应该包含:

use super::sub_folder;

或者,等效地(绝对路径而不是相对路径),

use crate::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 your mod declarations and your file locations match up to each other.

So, if the path is src/sub_folder/mod.rs (or src/sub_folder.rs), then you should declare the module in main.rs because main.rs (or lib.rs if you are doing that instead) is the crate root, the place where all top-level modules are declared. That is, main.rs contains

mod sub_folder;
mod sub_mod;

These two modules are siblings within the crate. Then in order for sub_mod to import (not define) sub_folder, it should contain:

use super::sub_folder;

or, equivalently (absolute rather than relative path),

use crate::sub_folder;

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, write mod 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文