Why do I get “overflow evaluating the requirement” when rewriting a function using Diesel's traits into a trait method?

断了今生、忘了曾经 提交于 2021-02-08 05:14:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!