gpt4 book ai didi

rust - Hyper 编译错误

转载 作者:行者123 更新时间:2023-11-29 08:18:55 28 4
gpt4 key购买 nike

我遇到了一个编译错误,我对 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 的新实例对于 hyper,因此实现 NewService 似乎很有意义,但我不明白为什么需要执行 Fn() . NewService实际上是为 Fn() -> io::Result<Service 实现的所以也许这在某种程度上发生了冲突?

有一个完整的示例项目 here .

最佳答案

您已经为 MyServer 实现了 NewService 但是您提供的 bind 一个 &MyServer 它找不到实现NewService 的。

你选择的解决方案在很大程度上取决于你为什么要这样做,但你可以为 &MyServer 实现 NewService:

impl<'a> NewService for &'a MyServer {
...
}

关于rust - Hyper 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43370173/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com