1
我遇到了一個編譯錯誤,我不太瞭解從一個Hyper的master
分支的例子的輕微修改。考慮下面的代碼:編譯錯誤與Hyper
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。
基本相同,http://stackoverflow.com/q/40922505/ 155423 – Shepmaster