问题
I am trying to add pagination using Diesel. The compiler is able to check bounds on a generic type if I use a function but isn't if I try to do the same as an implementation of a trait.
This is a simple working example:
use diesel::query_dsl::methods::{LimitDsl, OffsetDsl};
pub fn for_page<T>(query: T)
where
T: OffsetDsl,
T::Output: LimitDsl,
{
query.offset(10).limit(10);
}
OffsetDsl and
LimitDsl are Diesel's traits which provides the methods offset
and limit
.
When I try to extract this method as a trait and implement it like this
use diesel::query_dsl::methods::{LimitDsl, OffsetDsl};
trait Paginator {
fn for_page(self);
}
impl<T> Paginator for T
where
T: OffsetDsl,
<T as OffsetDsl>::Output: LimitDsl,
{
fn for_page(self) {
self.offset(10).limit(10);
}
}
I get a not very clear error message.
error[E0275]: overflow evaluating the requirement `<Self as diesel::query_dsl::offset_dsl::OffsetDsl>::Output`
--> src/main.rs:3:1
|
3 | / trait Paginator {
4 | | fn for_page(self);
5 | | }
| |_^
|
= note: required because of the requirements on the impl of `Paginator` for `Self`
note: required by `Paginator`
--> src/main.rs:3:1
|
3 | trait Paginator {
| ^^^^^^^^^^^^^^^
error[E0275]: overflow evaluating the requirement `<Self as diesel::query_dsl::offset_dsl::OffsetDsl>::Output`
--> src/main.rs:4:5
|
4 | fn for_page(self);
| ^^^^^^^^^^^^^^^^^^
|
= note: required because of the requirements on the impl of `Paginator` for `Self`
note: required by `Paginator`
--> src/main.rs:3:1
|
3 | trait Paginator {
| ^^^^^^^^^^^^^^^
I understand that this means that the compiler cannot check the condition on T::Output
, but it's not clear what is the difference with a simple function with the same condition.
I'm using Rust 1.35.0 and Diesel 1.4.
回答1:
I cannot answer why they differ. I can say that repeating the bounds on the trait definition compiles:
use diesel::query_dsl::methods::{LimitDsl, OffsetDsl};
trait Paginator
where
Self: OffsetDsl,
Self::Output: LimitDsl,
{
fn for_page(self);
}
impl<T> Paginator for T
where
T: OffsetDsl,
T::Output: LimitDsl,
{
fn for_page(self) {
self.offset(10).limit(10);
}
}
You may also be interested in the extending Diesel guide, which discusses how best to add a paginate
method.
来源:https://stackoverflow.com/questions/56341062/why-do-i-get-overflow-evaluating-the-requirement-when-rewriting-a-function-usi