Rust 如何使用默认处理程序将hyper::server::server存储为构造函数中的结构字段?

Rust 如何使用默认处理程序将hyper::server::server存储为构造函数中的结构字段?,rust,hyper,Rust,Hyper,我正在尝试将hyper::server::server存储为我的结构的成员(struct MyApp)。例如,我可以从程序的main()函数中执行此操作 如何在结构的MyApp::new()方法中执行此操作?我想我需要MyApp中F的具体类型。然而,尽管尝试过,我还是无法(正确地)为这个闭包指定具体的类型 我不知道该怎么做。我认为Box通过允许我将闭包作为一个具体类型进行传递,将闭包绑定起来是可行的,事实上,当我在main()中执行此操作时,闭包就可以了,而不是MyApp::new()。我希望在

我正在尝试将
hyper::server::server
存储为我的结构的成员(
struct MyApp
)。例如,我可以从程序的
main()
函数中执行此操作

如何在结构的
MyApp::new()
方法中执行此操作?我想我需要
MyApp
F
的具体类型。然而,尽管尝试过,我还是无法(正确地)为这个闭包指定具体的类型

我不知道该怎么做。我认为
Box
通过允许我将闭包作为一个具体类型进行传递,将闭包绑定起来是可行的,事实上,当我在
main()
中执行此操作时,闭包就可以了,而不是
MyApp::new()
。我希望在stable rust中有一种方法可以做到这一点,因为我真的很想实现一个包含超级服务器的结构

这是我的结构:

struct MyApp<F> {
    hyper_server: Server<MyBoxedClosure<F>, hyper::Body>,
}
如果我创建了一个
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!");
}
impl MyApp
哪里
F:Fn()->std::result::result+Send+Sync,
{
fn new()->MyApp{
让mbc=MyBoxedClosure{value:Box::new(| | Ok(HelloWorld))};
让addr=“127.0.0.1:3000”;
让hyper_server=Http::new().bind(&addr,mbc).unwrap();
MyApp{hyper_服务器:hyper_服务器}
}
}
fn main(){
让_my_app=MyApp::new();
println!(“你好,世界!”);
}
编译器错误如下:

错误[E0308]:类型不匹配
-->src/main.rs:56:9
|
56 | MyApp{hyper_服务器:hyper_服务器}
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^所需的类型参数,已找到闭包
|
=注意:应为'MyApp'类型`
找到类型`MyApp`

您创建的泛型函数应返回用户想要的任何类型
fn new()->MyApp
,但您返回的是具体类型,而不是
F
@AndrewStraw闭包与否并不重要。导入您告诉我的
fn new()->MyApp
I返回您想要的任何类型,然后返回conrete类型。请注意,您的签名允许像这样调用a=MyApp:::new(),而您的
new
显然不会返回
MyApp
右侧。现在它是的副本。@AndrewStraw您应该重做代码,最简单的方法是删除
F
completly make
MyBoxedClosure
concrete type with
Box
something as field。。正如@user1034749所提到的,用装箱的trait对象替换type参数是当前返回闭包的最佳方式。
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!");
}