Rust如何从上层目录的其他文件夹中导入指定函数
解决步骤
第一步:确认模块导出配置
- 检查
src/paas_core/mod.rs,必须添加如下内容导出create子模块:
pub mod create;
- 检查
create.rs里需要被外部调用的函数/结构体,必须添加pub关键字声明为公开项,示例:
// create.rs pub fn create_resource() { // 业务逻辑 }
- 检查
src/main.rs,必须声明两个顶层模块,Rust不会自动识别目录下的rs文件为模块,需要手动声明:
mod paas_core; mod rest_api;
- 检查
src/rest_api/mod.rs,必须声明rest子模块:
pub mod rest;
第二步:在rest.rs中导入对应项
有两种导入方式均可生效,更推荐绝对路径写法,避免相对路径层级搞错:
- 绝对路径写法(从crate根开始定位):
// rest.rs use crate::paas_core::create::create_resource; // 调用示例 fn test() { create_resource(); }
- 相对路径写法:
// rest.rs use super::paas_core::create::create_resource; // 调用示例 fn test() { create_resource(); }
常见失效原因
- 漏在
main.rs中声明paas_core顶层模块,编译器无法识别该模块存在 paas_core/mod.rs中导出create时没加pub,外部模块无权访问- 目标函数/结构体没加
pub关键字,即使找到模块也无法访问内部项
内容的提问来源于stack exchange,提问作者prnvbn
相关产品推荐
相关产品推荐

