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

相关推荐
The Future is mine2 分钟前
C# new Bitmap(32043, 32043, PixelFormat.Format32bppArgb)报错:参数无效,如何将图像分块化处理?
开发语言·c#
亿坊电商4 分钟前
PHP框架在微服务迁移中能发挥什么作用?
开发语言·微服务·php
烁3474 分钟前
每日一题(小白)模拟娱乐篇33
java·开发语言·算法
uhakadotcom14 分钟前
Lovable:用AI轻松打造完整应用,零基础也能快速开发
后端·面试·架构
小希爸爸15 分钟前
4、中医基础入门和养生
前端·后端
码起来呗21 分钟前
基于SpringBoot的高校学习讲座预约系统-项目分享
spring boot·后端·学习
坐吃山猪23 分钟前
Python-Agent调用多个Server-FastAPI版本
开发语言·python·fastapi
88号技师25 分钟前
【1区SCI】Fusion entropy融合熵,多尺度,复合多尺度、时移多尺度、层次 + 故障识别、诊断-matlab代码
开发语言·机器学习·matlab·时序分析·故障诊断·信息熵·特征提取
Asthenia041227 分钟前
Reactor 模型详解:从单线程到多线程及其在 Netty 和 Redis 中的应用
后端
北漂老男孩40 分钟前
Java对象转换的多种实现方式
java·开发语言