Rust unresolved import `crate::xxx` 报错解决

问题阐述

该问题出现在我使用actix编写的crud后端api中,我的后端结构如下:

bash 复制代码
D:.
|   handle_err.rs
|   lib.rs
|   main.rs
|
+---application
|       mod.rs
|       user_service.rs
|
+---domain
|       dto.rs
|       mod.rs
|       user.rs
|
+---infrastructure
|       mod.rs
|       repository.rs
|
\---interface
        mod.rs
        user_controller.rs

我希望在 `user_service.rs` 和 `repository.rs` 中使用我的自定义error结构体对象,我在 `application`目录下和 `infrastructure` 目录下的 mod.rs 中都已经导出了对应 .rs 文件:

rust 复制代码
pub mod repository;
rust 复制代码
pub mod user_service;

并且在lib.rs目录下也已经导出了对应包:

rust 复制代码
pub mod infrastructure;
pub mod domain;
pub mod application;
pub mod handle_err;

但是在 `repository.rs` 文件中的引入

rust 复制代码
use crate::handle_err::ServiceError;

却报错:

unresolved import `crate::handle_err`

unresolved importrustcClick for full compiler diagnostic

解决方案

main.rs 中 mod base即可,即在man.rs 中添加 mod handle_err;

rust 复制代码
use actix_web::{web, App, HttpServer};
use dotenv::dotenv;
use mysql::Pool;
use std::env;
use std::sync::Arc;

mod domain;
mod application;
mod infrastructure;
mod interface;
mod handle_err;

use application::user_service::UserService;
use infrastructure::repository::UserRepository;
use interface::user_controller::configuration;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    dotenv().ok();
    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = Pool::new(database_url).expect("Failed to create database pool");

    let user_repository = UserRepository::new(pool);
    let user_service = Arc::new(UserService::new(user_repository));

    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::from(user_service.clone()))
            .configure(configuration) // 调用配置函数注册路由
    })
    .bind(("127.0.0.1", 8081))?
    .run()
    .await
}

参考资料

Rust 使用 use::create:: 不能引用顶级目录的模块?? - Rust语言中文社区

相关推荐
代码无疆13 小时前
学点java字节码更易于理解一些特殊的java语法效果
java·后端
武汉唯众智创14 小时前
职业院校C语言程序设计(AIGC版)课程教学解决方案
c语言·开发语言·aigc·程序设计·c语言程序设计·c语言程序设计实训室
qq_4017004114 小时前
C语言void*
c语言·开发语言
sg_knight14 小时前
Python 面向对象基础复习
开发语言·python·ai编程·面向对象·模型
星浩AI14 小时前
AI 并不懂文字,它只认向量:一文搞懂 Embedding
后端
程序员博博14 小时前
这才是vibe coding正确的打开方式 - 手把手教你开发一个MCP服务
javascript·人工智能·后端
90后的晨仔14 小时前
阿里云服务器如何给子账号设置指定具体的那一台服务器?
后端
期待のcode14 小时前
springboot热部署
java·spring boot·后端
expect7g14 小时前
Paimon源码解读 -- FULL_COMPACTION_DELTA_COMMITS
大数据·后端·flink
踏浪无痕15 小时前
周末拆解:QLExpress 如何做到不编译就能执行?
后端·算法·架构