You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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中导入对应项

有两种导入方式均可生效,更推荐绝对路径写法,避免相对路径层级搞错:

  1. 绝对路径写法(从crate根开始定位):
// rest.rs
use crate::paas_core::create::create_resource;

// 调用示例
fn test() {
    create_resource();
}
  1. 相对路径写法:
// 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:06:03