嵌套关闭借用失败

时间:2018-09-19 03:24:09

标签: rust yaml hyper

我想解析一个YAML文件,并将服务内部的值用于HTTP请求。第35行是main函数的结尾。

extern crate hyper;
extern crate libc;
extern crate yaml_rust;

use hyper::rt::Future;
use hyper::service::service_fn_ok;
use hyper::{Body, Response, Server};
use std::sync::Arc;
use yaml_rust::YamlLoader;

fn main() {
    let content: String = String::from("response: Hello world");
    let cfg = Arc::new(YamlLoader::load_from_str(content.as_str()).unwrap());
    let cfg0 = (&cfg[0]).clone();
    let cfg_response = (&cfg0)["response"].as_str().unwrap();

    // A `Service` is needed for every connection, so this
    // creates on of our `hello_world` function.
    let handle = move || {
        let cfg_response = cfg_response.clone();

        service_fn_ok(move |_| Response::new(Body::from(String::from(cfg_response.clone()))))
    };

    // Serve HTTP protocol
    // This is our socket address...
    let addr: std::net::SocketAddr = ([127, 0, 0, 1], 3000).into();

    let server = Server::bind(&addr)
        .serve(handle)
        .map_err(|e| eprintln!("server error: {}", e));

    // Run this server for... forever!
    hyper::rt::run(server);
}

不幸的是,我遇到了一个嵌套的闭包,导致一个奇怪的借用错误:

error[E0597]: `cfg0` does not live long enough
  --> src/main.rs:15:26
   |
15 |     let cfg_response = (&cfg0)["response"].as_str().unwrap();
   |                          ^^^^ borrowed value does not live long enough
...
35 | }
   | - borrowed value only lives until here
   |
   = note: borrowed value must be valid for the static lifetime...

我试图

  1. 克隆后再借用
  2. 使用Arc使其基于计数器,
  3. 修改分配

全部无济于事

为什么会这样?我该如何解决?

1 个答案:

答案 0 :(得分:0)

您将闭包传递到的函数-hyper::server::Builder::servehyper::rt::run()-要求其参数为'static,而不是受任何函数限制。 main在这方面并不特殊。

边界cfg_response的值由外部闭包捕获,因此嵌套闭包对于获取错误不是必需的。 这是一个有相同问题的非常小的程序:

fn main() {
    let cfg0 = String::from("hello world");
    let cfg_response: &str = &cfg0;

    let handle = move || {
        // this closure takes ownership of cfg_response, a reference to cfg0.  Since cfg0 will not
        // outlive the function, neither can handle.  If it instead took ownership of cfg0 or a
        // clone of it, it would have no outside references and could live forever.
        return cfg_response.to_owned();
    };

    serve(handle);
}

fn serve<F: Fn() -> String + 'static>(handle: F) {
    loop {
        println!("{}", handle());
    }
}

正如@Stargateur指出的那样,可以通过拥有cfg_response来解决。

或者,您可以像这样在lazy_static中初始化cfg0

#[macro_use]
extern crate lazy_static;

lazy_static! {
    static ref cfg0: String = String::from("hello world");
}

通过这种方式,您仍然可以使用借入的值,因为它符合生命周期要求。