【发布时间】:2018-02-13 10:41:39
【问题描述】:
我想使用 Hyper 来实现 Web 服务。我从the hello world example 复制了代码,它成功了。当我尝试将数据访问对象添加到 HelloWorld 结构时,出现错误,我不知道如何修复它。如何将 trait 成员添加到 Hyper 服务器?
extern crate futures;
extern crate hyper;
use futures::future::Future;
use hyper::header::ContentLength;
use hyper::server::{Http, Request, Response, Service};
trait Dao {}
struct MysqlDao;
impl Dao for MysqlDao {}
struct HelloWorld {
dao: Box<Dao>,
}
const PHRASE: &'static str = "Hello, World!";
impl Service for HelloWorld {
// boilerplate hooking up hyper's server types
type Request = Request;
type Response = Response;
type Error = hyper::Error;
// The future representing the eventual Response your call will
// resolve to. This can change to whatever Future you need.
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, _req: Request) -> Self::Future {
// We're currently ignoring the Request
// And returning an 'ok' Future, which means it's ready
// immediately, and build a Response with the 'PHRASE' body.
Box::new(futures::future::ok(
Response::new()
.with_header(ContentLength(PHRASE.len() as u64))
.with_body(PHRASE),
))
}
}
fn main() {
let addr = "127.0.0.1:3000".parse().unwrap();
let dao = Box::new(MysqlDao);
let server = Http::new().bind(&addr, || Ok(HelloWorld { dao })).unwrap();
server.run().unwrap();
}
错误信息:
error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce`
--> src/main.rs:44:42
|
44 | let server = Http::new().bind(&addr, || Ok(HelloWorld { dao })).unwrap();
| ---- ^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| the requirement to implement `Fn` derives from here
|
note: closure is `FnOnce` because it moves the variable `dao` out of its environment
--> src/main.rs:44:61
|
44 | let server = Http::new().bind(&addr, || Ok(HelloWorld { dao })).unwrap();
| ^^^
【问题讨论】:
-
不清楚你到底在问什么。编译器告诉您,您必须提供一种满足特定限制的类型,而您不是。也许您正在寻找When does a closure implement Fn, FnMut and FnOnce?为了在处理程序之间共享东西,也许你想要How do I share a HashMap between Hyper handlers?
-
@Shepmaster 非常感谢。我查看了您提供的链接,我认为这些不是我的情况。问题是“实现
Fn特征的闭包”,我不知道如何在 HelloWorld 中修复它! -
第二个链接非常接近您的问题,如果您完全理解第一个链接,您应该能够根据您的情况调整第二个链接的解决方案。或者换句话说,第一个链接解释了为什么会出现编译器错误,第二个链接解释了如何修复它。
-
@SebastianRedl,我仔细阅读了链接,我知道他们所说的内容,但我就是无法让它发挥作用。你能帮我修复我的代码吗?非常感谢!