为什么Rust多文件共享struct会报expected struct file1::A found struct file2::A错误?
报错产生原因
你在LoginRoute.rs和LoginService.rs中都通过#[path]属性将同一个Login.rs文件声明为了独立子模块:Rust中每一次mod xxx;声明都会生成一个完全独立的模块作用域,哪怕指向的是同一个源文件,两个模块内定义的同名结构体也会被判定为完全不相关的不同类型。
你代码中LoginRoute::Login::UserLoginResponse和LoginService::Login::UserLoginResponse属于两个不同模块下的独立类型,自然会出现类型不匹配的报错。
解决方案
按照Rust标准模块规则组织项目即可,不需要到处用#[path]硬指定模块路径,步骤如下:
- 第一步:删除所有文件中用
#[path]声明Login模块的代码 - 第二步:在每个子目录下新增
mod.rs文件声明目录下的模块:src/Models/mod.rs中写入pub mod Login;src/Routes/mod.rs中写入pub mod LoginRoute;src/Services/mod.rs中写入pub mod LoginService;
- 第三步:在项目入口
main.rs中声明顶层模块:pub mod Models; pub mod Routes; pub mod Services; - 第四步:所有需要用到
UserLoginResponse的地方,统一通过绝对路径导入同一结构体,在LoginRoute.rs和LoginService.rs头部都加上导入语句:use crate::Models::Login::UserLoginResponse; - 额外注意:你当前定义的
UserLoginResponse所有字段都是私有的,其他模块无法直接构造或访问字段,需要给需要公开的字段加上pub修饰:#[derive(Serialize, Deserialize, Debug)] pub struct UserLoginResponse { pub id: i32, pub username: String, pub token: String }
修改完成后两个文件调用的就是同一个结构体,类型匹配后报错就会消失。
内容的提问来源于stack exchange,提问作者Gonzalo
相关产品推荐
相关产品推荐

