< 返回版块

demisstif 发表于 2019-09-18 21:26

代码如下:

 // https://api.btcgateway.pro/api/v1/contract_contract_info
     fn request_data<'de, T>(&'de self, uri: &str, m: Method, body: Body) -> impl Future<Item=T, Error=FetchError>
        where T: Deserialize<'de>
    {
        let req = Request::builder()
            .method(m)
            .uri(uri)
            .body(body)
            .unwrap();

        let https = hyper_tls::HttpsConnector::new(4).unwrap();
        let client = hyper::Client::builder().build::<_, hyper::Body>(https);

        client.request(req)
            .and_then(|resp|{
                println!("{}", resp.status());
                resp.into_body().concat2()
            })
            .from_err::<FetchError>()
            .and_then(|body| {
//                io::stdout().write_all(&body)
//                    .map_err(|e| panic!("example expects stdout is open, error={}", e));
                let info = serde_json::from_slice(&body)?;
                Ok(info)
            })
            .from_err()

    }

    pub fn get_contract_info(&self) {
        let uri = String::from("https://api.btcgateway.pro/api/v1/contract_contract_info");
//        let fut = self.request_data::<RespContractInfo>("https://api.btcgateway.pro/api/v1/contract_contract_info", Method::GET, Body::from(""))
        let fut = self.request_data::<RespContractInfo>(&uri, Method::GET, Body::from(""))
            .map(|info| {
                println!("{:#?}", info);
            })
            .map_err(|e| {
                match e {
                    FetchError::Http(e) => eprintln!("http error: {}", e),
                    FetchError::Json(e) => eprintln!("json parsing error: {}", e),
                }
            });
        rt::run(fut);
    }

在main中调用get_contract_info()时,编译不通过,会报以下的错误

error[E0597]: `body` does not live long enough
   --> antenna\src\hbdm.rs:120:51
    |
99  |      fn request_data<'de, T>(&'de self, uri: &str, m: Method, body: Body) -> impl Future<Item=T, Error=FetchError>
    |                      --- lifetime `'de` defined here
...
120 |                 let info = serde_json::from_slice(&body)?;
    |                            -----------------------^^^^^-
    |                            |                      |
    |                            |                      borrowed value does not live long enough
    |                            argument requires that `body` is borrowed for `'de`
121 |                 Ok(info)
122 |             })
    |             - `body` dropped here while still borrowed

这是为什么?如何解决呢?

评论区

写评论
wllenyj 2019-09-19 14:48

https://stackoverflow.com/questions/35592750/how-does-for-syntax-differ-from-a-regular-lifetime-bound

作者 demisstif 2019-09-19 13:59

非常感谢,改了以后成功编译了。但这是为什么呢?或者这里涉及的知识是什么?我想弄明白 对以下内容的回复:

Dengjianping 2019-09-18 22:37
where T: for<'de> Deserialize<'de>
1 共 3 条评论, 1 页