我遇到了编译错误,我不太了解Hyper的master
分支中的示例略有修改。给出以下代码:
extern crate futures;
extern crate hyper;
use futures::future::FutureResult;
use hyper::header::{ContentLength, ContentType};
use hyper::server::{Http, Service, Request, Response, Server, NewService};
use hyper::Body;
use std::fmt::Display;
use std::result;
static PHRASE: &'static [u8] = b"Hello World!";
#[derive(Clone, Copy)]
pub struct MyService {}
impl Service for MyService {
type Request = Request;
type Response = Response;
type Error = hyper::Error;
type Future = FutureResult<Response, hyper::Error>;
fn call(&self, _req: Request) -> Self::Future {
return futures::future::ok(Response::new()
.with_header(ContentLength(PHRASE.len() as u64))
.with_header(ContentType::plaintext())
.with_body(PHRASE));
}
}
#[derive(Clone)]
pub struct MyServer {}
#[derive(Debug)]
pub struct MyServeError(String);
impl<T: Display> From<T> for MyServeError {
fn from(e: T) -> MyServeError {
return MyServeError(format!("{}", e));
}
}
type Result<T> = result::Result<T, MyServeError>;
impl MyServer {
pub fn new() -> MyServer {
return MyServer {};
}
fn get_server(&self) -> Result<Server<&MyServer, Body>> {
let addr = format!("127.0.0.1:8080").parse()?;
return Ok(Http::new().bind(&addr, self)?);
}
}
impl NewService for MyServer {
type Request = Request;
type Response = Response;
type Instance = MyService;
type Error = hyper::Error;
fn new_service(&self) -> std::io::Result<Self::Instance> {
let service = MyService {};
Ok(service)
}
}
我收到此编译错误:
Compiling hyper-problem-demo v0.1.0 (file:///.../hyper-problem-demo)
error[E0277]: the trait bound `MyServer: std::ops::Fn<()>` is not satisfied
--> src/lib.rs:50:31
|
50 | return Ok(Http::new().bind(&addr, self)?);
| ^^^^ the trait `std::ops::Fn<()>` is not implemented for `MyServer`
|
= note: required because of the requirements on the impl of `std::ops::FnOnce<()>` for `&MyServer`
= note: required because of the requirements on the impl of `hyper::server::NewService` for `&MyServer`
error[E0277]: the trait bound `MyServer: std::ops::FnOnce<()>` is not satisfied
--> src/lib.rs:50:31
|
50 | return Ok(Http::new().bind(&addr, self)?);
| ^^^^ the trait `std::ops::FnOnce<()>` is not implemented for `MyServer`
|
= note: required because of the requirements on the impl of `hyper::server::NewService` for `&MyServer`
我真的不明白。我的目的只是使用MyServer
对象为超级创建MyService
的新实例,因此实现NewService
似乎有意义,但我不明白为什么会这样做要求实施Fn()
。 NewService
实际上是为Fn() -> io::Result<Service
实施的,所以可能会以某种方式发生冲突?
有一个完整的示例项目here。
答案 0 :(得分:1)
您已为NewService
实施了MyServer
,但是您提供的bind
&MyServer
无法找到NewService
的实施内容。
您选择的解决方案在很大程度上取决于您为什么要这样做,但您可以为NewService
实施&MyServer
:
impl<'a> NewService for &'a MyServer {
...
}