rust - 无法移出尝试反序列化 hyper::Request.body() 的借用内容

标签 rust borrow-checker hyper

我正在尝试使用 serde_json 将请求正文解析为强类型对象:

#[macro_use]
extern crate serde_derive; // 1.0.70
extern crate futures; // 0.1.23
extern crate hyper;   // 0.12.7
extern crate serde_json; // 1.0.24

use futures::{Future, Stream};
use hyper::{Body, Request};

struct AppError;

#[derive(Serialize, Deserialize)]
struct BasicLoginRequest {
    email: String,
    password: String,
}

impl BasicLoginRequest {
    fn from(req: Request<Body>) -> Result<BasicLoginRequest, AppError> {
        let body = req
            .body()
            .fold(Vec::new(), |mut v, chunk| {
                v.extend(&chunk[..]);
                futures::future::ok::<_, hyper::Error>(v)
            }).and_then(move |chunks| {
                let p: BasicLoginRequest = serde_json::from_slice(&chunks).unwrap();
                futures::future::ok(p)
            }).wait();

        Ok(body.unwrap())
    }
}

fn main() {}

我得到的错误是:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:20:20
   |
20 |           let body = req
   |  ____________________^
21 | |             .body()
   | |___________________^ cannot move out of borrowed content

来自 Cannot move out of borrowed content when unwrapping我知道展开时会发生此错误,因为需要一个值但提供了一个引用。 错误指向req.body();似乎 req.body() 返回一个引用,而不是一个值...

尝试处理正文的代码基于从 Extracting body from Hyper request as a string 中复制粘贴的摘录。

我如何使它工作?

最佳答案

我强烈建议阅读(至少略读)您使用的类型的文档,尤其是当您在使用它们时遇到问题时。

例如,Request::body定义为:

pub fn body(&self) -> &T

接下来的两个方法是

您想使用into_body

我还在我的网络浏览器中使用 Control-F 来搜索 -> T 一旦我知道非工作方法返回-> &T.

关于rust - 无法移出尝试反序列化 hyper::Request.body() 的借用内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51819892/

相关文章:

polymorphism - 为什么 Box<trait> 的大小与 Box<struct> 不同?

json - 如何将 Serde 与包含不同对象的 JSON 数组一起使用以获取成功和错误?

rust - Rust 中的隐式借用

rust - 我可以在 Rocket 中重复使用 Tokio Core 和 Hyper Client 吗?

rust - 元组struct构造函数提示私有(private)字段

reference - 有没有办法将引用类型克隆到拥有的类型中?

rust - 我可以从不可变的 BTreeMap 中获取值吗?

rust - 借用中间变量可绕过的错误

rust - "trait core::ops::Fn<(Request, Response)> is not implemented"将连接池传递给 Hyper 处理程序时关闭

rust - 使用 serde_json 反序列化远程结构的映射