rust - 无法创建 Iron 处理程序,因为不满足特征绑定(bind) std::ops::Fn<(&mut iron::Request)>

标签 rust iron

我正在尝试为 Iron 请求创建一个处理程序:

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();
}

但是编译器的响应是:

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`

我无法理解 Rust 对我说的话。

最佳答案

这是您的问题的重现;你能发现问题吗?

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() {}

放弃?

您已经为您的结构实现了该特征:

impl Handler for Server

但是然后尝试使用对结构引用的引用,这没有实现该特征:

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

所以这是行不通的。您需要重组代码或实现对结构的引用的特征。

关于rust - 无法创建 Iron 处理程序,因为不满足特征绑定(bind) std::ops::Fn<(&mut iron::Request)>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40922505/

相关文章:

rust - Rust 中的 "()"类型是什么?

rust - 令人困惑的 Arc 自动取消引用

rust - 使用 Iron Params 访问表单上传的文件路径

rust - 使用铁框架,如何退出监听循环?

rust - 如何更改 Iron 的默认 404 行为?

Rust 泛型参数和编译时间 if

使用rust 柴油机 : the trait bound `NaiveDateTime: Deserialize<' _>` is not satisfied

rust - Arcs 中的元组如何用引用解构?

multithreading - 如何在 Iron 框架中启用线程功能?