我正在尝试将 a 存储hyper::server::Server
为我的结构的成员(struct MyApp
如下)。例如,我可以从我的程序的main()
功能中做到这一点。
我怎样才能在我的结构的MyApp::new()
方法中做到这一点?我想我需要in的具体类型。然而,尽管尝试,我无法(正确地)为这个闭包指定一个具体的类型。F
MyApp<F>
我不知道该怎么做。我认为Box
闭包可以通过允许我将闭包作为具体类型传递来起作用,并且当我在 中执行此操作时确实如此main()
,但不是MyApp::new()
。我希望有一种方法可以在稳定的 rust 中做到这一点,因为我真的很想实现一个包含超级服务器的结构。
这是我的结构:
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]>`