我正在尝试为我正在构建的应用程序松散地实现存储库模式,但是我似乎偶然遇到了某种递归类型定义。
在以下代码上:
use diesel::{pg::Pg, Insertable, Queryable, QueryDsl, PgConnection, Identifiable, Table};
use std::marker::PhantomData;
use anyhow::anyhow;
pub struct Repository<Entity, SqlType, Tab> {
_entity_phantom: PhantomData<Entity>,
_type_phantom: PhantomData<SqlType>,
table: Tab,
}
impl <Entity, SqlType, Tab> Repository<Entity, SqlType, Tab>
where
Entity: Queryable<SqlType, Pg> + Insertable<Tab> + Identifiable,
Tab: Table
{
fn find_by_id(&self, id: i64, conn: &PgConnection) -> anyhow::Result<Entity> {
match self.table.find(id).first::<Entity>(conn) {
Ok(entity) => Ok(entity),
Err(e) => Err(anyhow!("{}", e)),
}
}
}
我得到错误:error[E0275]: overflow evaluating the requirement `_: Sized`
--> support/src/lib.rs:18:26
|
18 | match self.table.find(id).first::<Entity>(conn) {
| ^^^^
|
= help: consider adding a `#![recursion_limit="256"]` attribute to your crate (`support`)
= note: required because of the requirements on the impl of `FilterDsl<_>` for `<Tab as AsQuery>::Query`
我试过增加箱子顶部的递归限制,但无济于事。洒水+ Sized
在整个特征范围内,似乎也没有做任何事情。我错过了什么?
最佳答案
此类错误通常意味着 diesel
由于限制不够,无法解决您的特征界限。
Diesel 泛型编程通常有点复杂,但这里有一些提示可以在下次遇到此错误时帮助您:
find
,你必须确保你 还有检查相同的界限! Find
。或 Limit
在下面的代码中 Limit<Find<..>>
,对于您在查询链中调用的每个新方法,您都需要指定它。 use anyhow::anyhow;
use diesel::{
associations::HasTable,
dsl::{Find, Limit},
query_dsl::{
methods::{FindDsl, LimitDsl},
LoadQuery,
},
PgConnection, RunQueryDsl, Table,
};
use std::marker::PhantomData;
pub struct Repository<Entity, Tab> {
_entity_phantom: PhantomData<Entity>,
_table_phantom: PhantomData<Tab>,
}
impl<Entity, Tab> Repository<Entity, Tab>
where
Entity: HasTable<Table = Tab>,
Tab: Table,
{
fn find_by_id(&self, id: i64, conn: &PgConnection) -> anyhow::Result<Entity>
where
Tab: LimitDsl + FindDsl<i64>,
Find<Tab, i64>: LimitDsl + Table,
Limit<Find<Tab, i64>>: LoadQuery<PgConnection, Entity>,
{
match Entity::table().find(id).first::<Entity>(conn) {
Ok(entity) => Ok(entity),
Err(e) => Err(anyhow!("{}", e)),
}
}
}
What am I missing?
一般来说,人们可以猜到你试图做什么,我不认为你没有达到预期的结果是你的错。这种泛型编程很难理解,而且有各种类型及其名称
T
, U
很容易迷路。Entity
如果我正确理解 Entity
是错误的指:Queryable<Query, Database>
表示可以在 Database
中查询其实现的类型通过Query
. “传入”类型 SqlQuery
没有意义如果您也不传递具体类型! Insertable<Tab>
我认为是其他方法的遗留物吗? Identifiable
也? 关于rust - 尝试使用 Diesel 查询时溢出评估需求 `_: Sized`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67659872/