Generics 锈蚀:E0562,在实施通用特性时

Generics 锈蚀:E0562,在实施通用特性时,generics,rust,traits,Generics,Rust,Traits,我正在试着除锈和除锈❤️ 到目前为止还没有 但目前我仍停留在一般特征上:) 现状: 我想实现这个特性,但我无法修改: pub特征处理程序{ fn运行(&mut self,事件:http::Request)->结果; } 该特性在同一个库中的一个实现是: 函数的impl处理程序 哪里 函数:FnMut(http::Request)->Result, { fn运行(&mut self,事件:http::Request)->结果{ (*自我)(事件) } } 此实现可按如下方式使用: fn处理程序

我正在试着除锈和除锈❤️ 到目前为止还没有

但目前我仍停留在一般特征上:)

现状:

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

pub特征处理程序{
fn运行(&mut self,事件:http::Request)->结果;
}
该特性在同一个库中的一个实现是:

函数的impl处理程序 哪里 函数:FnMut(http::Request)->Result, { fn运行(&mut self,事件:http::Request)->结果{ (*自我)(事件) } } 此实现可按如下方式使用:

fn处理程序(请求:http::Request)->结果{
...
}
语调回答
特征:

pub响应{
fn进入_反应(自我)->反应;
}
我想做什么:

我想实现这个特性,使结构能够与上面提到的类型一起使用

我试过:

GQLHandler的impl处理程序{ fn运行(&mut self,req:http::Request)->结果{ ... } } 但这会导致错误:

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> {
   |                                                           ^^^^^^^^^^^^^^^^^

即使我为
Response
实现了
IntoResponse

trait响应{
fn foo(和self);
}
impl为响应输入响应
{
fn foo(&self){}
}

我遗漏了什么?

新答案

感觉就像你在寻找:

现在,无法从Trait实现返回
impl Trait
类型。这是RFC修复的一个巨大限制

已合并,但实现不稳定。您可以跟踪进度

原始答案

您不能在此处使用
impl
,但可以通过以下方式解决此问题:

GQLHandler的impl处理程序{ fn运行(&mut self,req:http::Request)->结果{ // ... } }
删除了我之前的评论,因为我相应地更新了原始问题。嘿@thlcodes,你能解释一下你为什么试图避免
结果
方法吗?这个解释应该能帮我找到最适合你的答案
IntoResponse
也为
Into
甚至
serde_json::Value
实现,我也希望将它们用于更干净的代码。但我主要想了解为什么这不起作用,并了解:)@thlcodes,我已经更新了答案。请看一看。在您的示例中,我无法返回实现
IntoResponse
的对象。给你。我得到“预期类型参数
T
,找到结构
Return
”,尽管我认为
Return
T
。我做错了什么?
  |
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<()>`
impl<T: IntoResponse> Handler<T, Body, MyError> for GQLHandler {
    fn run(&mut self, req: http::Request<Body>) -> Result<T, MyError> {
        // ...
    }
}