Cannot create an Iron handler because the trait bound std::ops::Fn<(&mut iron::Request)> is not satisfied

时光毁灭记忆、已成空白 提交于 2019-12-11 03:25:56

问题


I'm trying to create a handler for Iron requests:

extern crate iron;
extern crate mount;

use iron::{Iron, Request, Response, IronResult, status};
use mount::Mount;
use iron::middleware::Handler;

struct Server {
    message: String
}

impl Server {
    pub fn start(&self){
        let mut mount = Mount::new();
        mount.mount("/", &self);
        Iron::new(mount).http("0.0.0.0:3000").unwrap();
    }
}

impl Handler for Server {
    fn handle(&self, _req: &mut Request) -> IronResult<Response>{
        Ok(Response::with((status::Ok, self.message)))
    }
}

fn main() {
    Server{message: "test".to_string()}.start();
}

but compiler response is:

error[E0277]: the trait bound `for<'r, 'r, 'r> Server: std::ops::Fn<(&'r mut iron::Request<'r, 'r>,)>` is not satisfied
  --> src/main.rs:15:15
   |
15 |         mount.mount("/", &self);
   |               ^^^^^ trait `for<'r, 'r, 'r> Server: std::ops::Fn<(&'r mut iron::Request<'r, 'r>,)>` not satisfied
   |
   = note: required because of the requirements on the impl of `std::ops::FnOnce<(&mut iron::Request<'_, '_>,)>` for `&Server`
   = note: required because of the requirements on the impl of `iron::Handler` for `&&Server`

I was unable to understand what Rust is saying to me.


回答1:


Here's a reproduction of your issue; can you spot the problem?

trait Foo {}

struct Bar;

impl Foo for Bar {}

impl Bar {
    fn thing(&self) {
        requires_bar(self);
    }
}

fn requires_bar<F>(foo: F) where F: Foo {}

fn main() {}

Give up?

You've implemented the trait for your struct:

impl Handler for Server

But are then trying to use a reference to a reference to your struct, which does not implement the trait:

pub fn start(&self) {
    // ...
    mount.mount("/", &self);
    // ...
}

So that cannot work. You need to restructure your code or implement the trait for a reference to your struct.



来源:https://stackoverflow.com/questions/40922505/cannot-create-an-iron-handler-because-the-trait-bound-stdopsfnmut-ironr

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