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

相关推荐
少许极端2 小时前
算法奇妙屋(七)-字符串操作
java·开发语言·数据结构·算法·字符串操作
懒羊羊不懒@2 小时前
Java基础语法—字面量、变量详解、存储数据原理
java·开发语言
Code blocks2 小时前
GB28181视频服务wvp部署(一)
java·spring boot·后端
我命由我123452 小时前
Spring Boot - Spring Boot 静态资源延迟响应(使用拦截器、使用过滤器、使用 ResourceResolver)
java·spring boot·后端·spring·java-ee·intellij-idea·intellij idea
小龙报2 小时前
《算法通关指南---C++编程篇(2)》
c语言·开发语言·数据结构·c++·程序人生·算法·学习方法
古一|2 小时前
Vue3中ref与reactive实战指南:使用场景与代码示例
开发语言·javascript·ecmascript
华仔啊3 小时前
3 分钟让你彻底搞懂 Spring 观察者和发布者模式的本质区别
java·后端
言之。3 小时前
LiteLLM:让LLM调用变得简单统一
后端·python·flask
宠友信息3 小时前
java微服务驱动的社区平台:友猫社区的功能模块与实现逻辑
java·开发语言·微服务
驰羽3 小时前
[GO]golang接口入门:从一个简单示例看懂接口的多态与实现
开发语言·后端·golang