简体   繁体   English

实现actix-web的Handler时找不到关联的类型`Context`

[英]associated type `Context` not found when implementing actix-web's Handler

I have the following code based on the actix-web Database Integration sample . 我有以下基于actix-web数据库集成示例的代码

extern crate actix;
extern crate actix_web;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_mysql;

use actix::prelude::*;
use actix_web::{middleware::Logger, server, App, FutureResponse, HttpRequest, HttpResponse};

mod dbservices {

    use actix::prelude::*;
    use actix_web::dev::Handler;
    use model::DataDictionary;
    use r2d2::Pool;
    use r2d2_mysql::*;
    use std::io;

    pub struct MysqlConnection {
        db_pool: mysql::PooledConn,
    }

    impl Actor for MysqlConnection {
        type Context = SyncContext<Self>;
    }

    impl MysqlConnection {
        pub fn new(db_url: &str) -> MysqlConnection {
            unimplemented!();
        }
    }

    pub struct GetDD;
    impl Message for GetDD {
        type Result = io::Result<Vec<DataDictionary>>;
    }

    impl Handler<GetDD> for MysqlConnection {
        type Result = io::Result<Vec<DataDictionary>>;

        fn handle(&mut self, msg: GetDD, _: &mut Self::Context) -> Self::Result {
            unimplemented!();
        }
    }
}

mod model {
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct DataDictionary {
        id: i32,
        name: String,
    }
}

struct State {
    db: Addr<MysqlConnection>,
}

fn get_dd(req: HttpRequest<State>) -> FutureResponse<HttpResponse> {
    req.clone()
        .state()
        .db
        .send(GetDD)
        .from_err()
        .and_then(|result| Ok.json(result))
        .responder()
}

fn main() {
    std::env::set_var("RUST_LOG", "actix_web=debug,info");
    const db_url: str = "mysql://connstring";
    let addr = SyncArbiter::start(3, move || dbservices::MysqlConnection::new(db_url));

    server::new(|| {
        App::new()
            .middleware(Logger::default())
            .middleware(Logger::new("%a %{User-Agent}i"))
            .prefix("/api")
            .scope("/dd", |dp_scope| {
                dp_scope.resource("/", |r| r.h(dbservices::GetDD()))
            })
    }).bind("127.0.0.1:8088")
        .unwrap()
        .run();
}

I'm getting the following error when compiling. 编译时出现以下错误。 I'm not sure what I'm doing wrong: 我不确定自己在做什么错:

error[E0220]: associated type `Context` not found for `Self`
  --> src/main.rs:43:50
   |
43 |         fn handle(&mut self, msg: GetDD, _: &mut Self::Context) -> Self::Result {
   |                                                  ^^^^^^^^^^^^^ associated type `Context` not found

Here are my dependencies from Cargo.toml: 这是我对Cargo.toml的依赖:

[dependencies]
actix-web = "0.6.14"
actix = "0.6.1"
chrono = { version = "0.4.2", features = ["serde"] }
serde = "1.0.60"
serde_derive = "1.0.60"
serde_json = "1.0.17"
log = "0.4.1"
env_logger ="0.5.10"
futures = "0.2.1"
r2d2 = "*"

[dependencies.r2d2_mysql]
git = "https://github.com/outersky/r2d2-mysql"
version="*"

Creating a minimal MCVE almost always makes the problem easier to see: 创建最小的 MCVE几乎总是使问题更容易发现:

extern crate actix;
extern crate actix_web;

use actix::prelude::*;
use actix_web::dev::Handler;
use std::io;

pub struct MysqlConnection;

impl Actor for MysqlConnection {
    type Context = SyncContext<Self>;
}

pub struct DummyMessage;
impl Message for DummyMessage {
    type Result = io::Result<String>;
}

impl Handler<DummyMessage> for MysqlConnection {
    type Result = io::Result<String>;

    fn handle(&mut self, _: DummyMessage, _: &mut Self::Context) -> Self::Result {
        unimplemented!();
    }
}

fn main() {}
error[E0220]: associated type `Context` not found for `Self`
  --> src/main.rs:22:53
   |
22 |     fn handle(&mut self, _: DummyMessage, _: &mut Self::Context) -> Self::Result {
   |                                                   ^^^^^^^^^^^^^ associated type `Context` not found

Problem 1 — multiple versions 问题1 —多个版本

actix-web = "0.6.14"
actix = "0.6.1"

This brings in two different versions of actix: 这带来了两个不同版本的actix:

$ cargo tree -d

actix v0.5.8
└── actix-web v0.6.14
    └── repro v0.1.0 (file:///private/tmp/repro)

actix v0.6.1
└── repro v0.1.0 (file:///private/tmp/repro)

Pick a single one, actix 0.5.8. 选择一个,actix 0.5.8。

See also: 也可以看看:

Problem 2 — wrong trait 问题2 —错误的性格

You bring in actix_web::dev::Handler : 您引入actix_web::dev::Handler

pub trait Handler<S>: 'static {
    type Result: Responder;
    fn handle(&mut self, req: HttpRequest<S>) -> Self::Result;
}

You are implementing actix::Handler : 您正在实现actix::Handler

pub trait Handler<M> 
where
    Self: Actor,
    M: Message, 
{
    type Result: MessageResponse<Self, M>;
    fn handle(&mut self, msg: M, ctx: &mut Self::Context) -> Self::Result;
}

actix::Handler has Actor as its supertrait, which means that it can access the associated type Context . actix::HandlerActor为特征,这意味着它可以访问关联的Context类型。 actix_web::dev::Handler does not have the supertrait, so it doesn't know about Self::Context . actix_web::dev::Handler没有超级特性,因此它不了解Self::Context

Pick the appropriate trait and implement it correctly. 选择适当的特征并正确实施。

您可以使用SyncContext<Self>替换Self::Context

This is actually strange since there is only single associated type Context but for some reason Rust wants you to specify specifically associated type: <Self as Actor>::Context which should not be required since you have single Context type 这实际上很奇怪,因为只有单个关联类型Context但是出于某种原因Rust希望您指定专门关联的类型: <Self as Actor>::Context由于您只有单个Context类型,因此不需要

Are there any other errors that prevent your struct from compiling? 还有其他错误会阻止您的结构进行编译吗?

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

相关问题 Rust actix-web:特征 `Handler&lt;_, _&gt;` 未实现 - Rust actix-web: the trait `Handler<_, _>` is not implemented 迁移到 actix-web 3.0 时出错 - Errors when moving to actix-web 3.0 使actix-web终结点处理程序的HTML输出正确呈现的最简单方法是什么? - What's the easiest way to get the HTML output of an actix-web endpoint handler to be rendered properly? 尝试从actix-web路由处理程序功能内发出请求时出现错误“ BlockingClientInFutureContext” - Error “BlockingClientInFutureContext” when trying to make a request from within an actix-web route handler function Actix-web 2.0 JsonConfig error_handler 不工作 - Actix-web 2.0 JsonConfig error_handler not working 如何从带有客户端的actix-web处理程序向调用者返回错误? - How to return an error to caller from an actix-web handler with client? 如何在 Actix-web 中的 WebSocket 处理程序中正确调用异步函数 - How to correctly call async functions in a WebSocket handler in Actix-web actix-web app_data 在请求处理程序中始终为 None - actix-web app_data is always None in request handler 总是返回 Ok HttpResponse 然后在 actix-web 处理程序中工作 - Always return Ok HttpResponse then do work in actix-web handler 如何使用 actix-web 的 Json 类型解决“serde::Deserialize 的实现不够通用”? - How do I resolve "implementation of serde::Deserialize is not general enough" with actix-web's Json type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM