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

相关推荐
linux kernel7 分钟前
第七讲:C++中的string类
开发语言·c++
生无谓13 分钟前
什么是跨域,如何处理跨域
后端
Smilejudy15 分钟前
极具特色的位置运算
后端
码出极致15 分钟前
支付线上问题复盘的“5W”框架
后端
玩代码21 分钟前
Java线程池原理概述
java·开发语言·线程池
ezl1fe24 分钟前
RAG 每日一技(三):不止文本,代码和Markdown如何优雅地分块?
后端
jack_yin25 分钟前
手把手教你玩转 telegram-deepseek-bot 的 Admin 管理后台!
后端
浮游本尊26 分钟前
Java学习第8天 - Spring框架入门与依赖注入
后端
bcbnb26 分钟前
iOS App 安全加固实战:如何满足合规审计与选对加固工具
后端
00后程序员28 分钟前
WebView 调试太难?用远程调试工具这样搭建可控环境
后端