rust - 如何从上面文件夹中的另一个文件夹导入函数

标签 rust

我的目录结构是这样的

src
├── main.rs
├── paas_core
│   ├── create.rs
│   └── mod.rs
└── rest_api
    ├── mod.rs
    └── rest.rs

我想在名为 rest.rs 的文件中使用文件 create.rs 中声明的函数。我正在尝试使用 rest_api 模块中的模块,但我不知道该怎么做。

我尝试在 rest.rs 中使用 super::paas_core 但那没有用。

最佳答案

在文件中rest_api/rest.rs你必须使用use crate::paas_core;吗为了能够从 rest_api 引用到 paas_core 和 paas_core/mod.rs需要声明pub mod create;以确保您可以使用 paas_core::create::create_func(); 直接从 rest_api 调用函数

我希望它能解释清楚。一个完整的示例可能如下所示:

文件:main.rs

mod paas_core;
mod rest_api;

fn main() {
    rest_api::rest_func();
}

文件:rest_api/mod.rs


mod rest;

pub fn rest_func() {
    println!("rest_func() in rest_api/mod.rs called!");
    rest::rest_caller();
}

文件:rest_api/rest.rs

use crate::paas_core;
pub fn rest_caller() {
    println!("rest_caller() in rest_api/rest.rs called!");
    paas_core::create::create_func();
}

文件:paas_core/mod.rs

pub mod create;

文件:paas_core/create.rs

pub fn create_func() {
    println!("create_func() in paas_core/create.rs finally called!");
}

运行时的输出:

rest_func() in rest_api/mod.rs called!
rest_caller() in rest_api/rest.rs called!
create_func() in paas_core/create.rs finally called!

关于rust - 如何从上面文件夹中的另一个文件夹导入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69636018/

相关文章:

rust - 为什么用 git hash 替换依赖项的版本和路径属性会导致编译错误?

rust - 如何为结构的可变引用中的字段换入新值?

types - 以特定结构作为参数的特征实现

rust - Arc in Rust 中的临时生命周期

http - 如何使用 select.rs 从 HTML 文档中提取 "href"属性?

rust - 如何向 tokio-io 添加特殊的 NotReady 逻辑?

io - 如何惯用/高效地将数据从 Read+Seek 传输到 Write?

rust - 如何在捕获时向panick_info添加更多上下文?

运行 Rust 应用程序的 Azure 应用服务 Docker 容器发出出站 HTTP 请求 "unable to get local issuer certificate"

multithreading - 如何防止自动执行 Sync