繁体   English   中英

Rust:E0562 实现泛型特征时

[英]Rust: E0562 when implementing generic trait

到目前为止,我正在尝试 Rust 和 ❤️ 它。

但目前我坚持通用特征:)

现状:

我想实现这个特性,我无法修改:

pub trait Handler<R, B, E> {
    fn run(&mut self, event: http::Request<B>) -> Result<R, E>;
}

在同一个库中该特性的一种实现是:

impl<Function, R, B, E> Handler<R, B, E> for Function
where
    Function: FnMut(http::Request<B>) -> Result<R, E>,
{
    fn run(&mut self, event: http::Request<B>) -> Result<R, E> {
        (*self)(event)
    }
}

此实现可以按如下方式使用:

fn handler(req: http::Request<Body>) -> Result<impl IntoResponse, MyError> {
    ...
}

使用IntoReponse特性:

pub trait IntoResponse {
    fn into_response(self) -> Response<Body>;
}

我想做的事:

我想为结构实现该特征,以便能够与上述类型一起使用。

我试过:

impl Handler<impl IntoResponse, Body, MyError> for GQLHandler {
    fn run(&mut self, req: http::Request<Body>) -> Result<impl IntoResponse, MyError> {
        ...
    }
}

但这会导致错误:

error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
  --> handlers/gql.rs:18:14
   |
18 | impl Handler<impl IntoResponse, Body, NowError> for GQLHandler {
   |              ^^^^^^^^^^^^^^^^^

error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
  --> handlers/gql.rs:19:59
   |
19 |     fn run(&mut self, req: http::Request<Body>) -> Result<impl IntoResponse, NowError> {
   |                                                           ^^^^^^^^^^^^^^^^^

如果我为特定类型实现它,它会起作用,例如

impl Handler<http::Response<Body>, Body, NowError> for GQLHandler {
    fn run(&mut self, req: http::Request<Body>) -> Result<http::Response<Body>, NowError> {

但我想以某种方式保留impl Trait

期待任何建议。

感谢和干杯托马斯

编辑:

跟进@MaxV 的回答(谢谢!),遗憾的是这对我不起作用(这就是为什么我还没有接受这个答案)。

看到这个游乐场

当尝试使用实现IntoResponse的类型返回Ok(...) ,出现以下错误:

  |
3 | impl<T: IntoResponse> Handler<T, Body, MyError> for GQLHandler {
  |      - this type parameter
4 |     fn run(&mut self, req: Request<Body>) -> Result<T, MyError> {
5 |         Ok(Response::<()>::new(()))
  |            ^^^^^^^^^^^^^^^^^^^^^^^ expected type parameter `T`, found struct `http::Response`
  |
  = note: expected type parameter `T`
                     found struct `http::Response<()>`

即使我为Response实现了IntoResponse

trait IntoResponse{
    fn foo(&self);
}

impl IntoResponse for Response<()>
{
    fn foo(&self) {}
}

我错过了什么?

新答案

感觉就像你在寻找Existential 类型

现在,不可能从 trait 实现返回一个impl Trait类型。 这是一个巨大的限制,该 RFC 修复了<...>

存在类型 RFC已合并,但实现并不稳定。 您可以在那里跟踪进度。

原答案

你不能在那里使用impl但你可以通过这种方式解决它:

操场

impl<T: IntoResponse> Handler<T, Body, MyError> for GQLHandler {
    fn run(&mut self, req: http::Request<Body>) -> Result<T, MyError> {
        // ...
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM