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语言中文社区

相关推荐
大厂在职_QKT4 分钟前
C中静态库和动态库的使用
c语言·开发语言
优联前端37 分钟前
Web 音视频(四)在浏览器中处理音频
开发语言·javascript·音视频·优联前端·webav·webcodecs
南棱笑笑生40 分钟前
20250204将Ubuntu22.04的默认Dash的shell脚本更换为bash
开发语言·bash·dash
圆圆同学1 小时前
Springboot实现TLS双向认证
java·spring boot·后端
羚羊角uou1 小时前
【C++】多态详细讲解
开发语言·c++
利刃大大2 小时前
【C++】string类的模拟实现
开发语言·c++
数据小小爬虫2 小时前
利用 Python 爬虫获取按关键字搜索淘宝商品的完整指南
开发语言·爬虫·python
一只小松许️2 小时前
C++ CRTP:奇异递归模板模式的原理与应用
开发语言·c++
神秘的t2 小时前
javaEE初阶————多线程初阶(3)
java·开发语言
DY009J2 小时前
鸿蒙生态潮起:开发者的逐浪之旅
开发语言·华为·harmonyos