我正在尝试将hyper::server::Server
存储为我的结构(struct MyApp
下面的成员)。我可以通过例如我的程序main()
函数来完成此操作。
我如何在我的结构MyApp::new()
方法中执行此操作?我想我需要F
中MyApp<F>
的具体类型。但是,尽管尝试了,但我无法(正确地)为此闭包指定具体类型。
我无法弄清楚如何做到这一点。我认为Box
闭包可以通过允许我将闭包作为具体类型传递来实现,事实上,当我在main()
中执行此操作时,它会这样做,而不是MyApp::new()
。我希望有一种方法可以稳定生锈,因为我真的想实现一个包含超级服务器的结构。
这是我的结构:
struct MyApp<F> {
hyper_server: Server<MyBoxedClosure<F>, hyper::Body>,
}
以下是有效的完整代码 - 它会在MyApp.hyper_server
中设置main()
字段:
extern crate hyper;
extern crate futures;
use hyper::Error;
use hyper::server::{Http, Server, NewService, Service, Request, Response};
use hyper::header::ContentLength;
pub struct HelloWorld;
const PHRASE: &'static str = "Hello, World!";
impl Service for HelloWorld {
type Request = Request;
type Response = Response;
type Error = hyper::Error;
type Future = futures::future::FutureResult<Self::Response, Self::Error>;
fn call(&self, _req: Request) -> Self::Future {
futures::future::ok(
Response::new()
.with_header(ContentLength(PHRASE.len() as u64))
.with_body(PHRASE),
)
}
}
pub struct MyBoxedClosure<F> {
value: Box<F>,
}
impl<F> NewService for MyBoxedClosure<F>
where
F: Fn() -> std::result::Result<HelloWorld, std::io::Error>,
{
type Request = Request;
type Response = Response;
type Error = Error;
type Instance = HelloWorld;
fn new_service(&self) -> std::result::Result<Self::Instance, std::io::Error> {
self.value.new_service()
}
}
struct MyApp<F> {
hyper_server: Server<MyBoxedClosure<F>, hyper::Body>,
}
fn main() {
let mbc = MyBoxedClosure { value: Box::new(|| Ok(HelloWorld)) };
let addr = "127.0.0.1:3000".parse().unwrap();
let hyper_server = Http::new().bind(&addr, mbc).unwrap();
let my_app = MyApp { hyper_server: hyper_server };
println!("Hello, world!");
}
如果我创建一个MyApp::new()
函数并从main()
调用它,我就无法弄清楚如何避免编译错误。
impl<F> MyApp<F>
where
F: Fn() -> std::result::Result<HelloWorld, std::io::Error> + Send + Sync,
{
fn new() -> MyApp<F> {
let mbc = MyBoxedClosure { value: Box::new(|| Ok(HelloWorld)) };
let addr = "127.0.0.1:3000".parse().unwrap();
let hyper_server = Http::new().bind(&addr, mbc).unwrap();
MyApp { hyper_server: hyper_server }
}
}
fn main() {
let _my_app = MyApp::new();
println!("Hello, world!");
}
编译器错误是这样的:
error[E0308]: mismatched types
--> src/main.rs:56:9
|
56 | MyApp { hyper_server: hyper_server }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected type parameter, found closure
|
= note: expected type `MyApp<F>`
found type `MyApp<[closure@src/main.rs:53:52: 53:69]>`